1.创建的每一个函数,解析器都会向函数中添加一个prototype属性
var arr=[1,2,3];//toString();因为数组的原型上有toString()方法//push pop 因为数组原型上有console.log(arr.toString());//1,2,3/* 原型:1.obj.__proto__找到它的原型对象2.数组上的方法都是挂载在原型上(Array.prototype)的*/console.log(Array.prototype);console.log(arr.__proto__==Array.prototype);//true
2这个属性对应着一个对象,就是我们所谓的原型对象
原型对象:是某一类对象的基类,所有创建的对象都会共享该原型对象(共享机制)
作用:将对象的通用方法挂载在原型上
Student类
function Student(name,age){this.name=name;this.age=age;}Student.prototype.sayName=function(){console.log(this.name);}var s= new Student("小明",18);console.log(s) ;console.log(Student.prototype);
Teacher类
function Teacher(name,age){this.name=name;this.age=age;}Teacher.prototype.sayName=function(){console.log(this.name);}var p=new Teacher("lisa",18)console.log(p);
在原型对象上自定义方法
var arr=new Array(1,2,3);Array.prototype.sum=function(params){if(Array.isArray(params)){return params.reduce((a,b)=>a+b)}}console.log(arr.sum(arr));//6Array.prototype.http=function(){console.log("http");}arr.http();//http
