一、原型
1.定义:原型是function对象的一个属性,它定义了构造函数制造出的对象的公共祖先。
通过该构造函数产生的对象,可以继承该原型的属性和方法。原型也是对象。
2.利用原型特点和概念,可以提取公有属性
3.对象如何查看原型->隐式属性 __proto__
4.对象如何查看对象的构造函数 ->constructor
Person.prototype.name='su'; function Person(){ } var person =new Person(); //改变属性 Person.prototype.name='yue'; console.log(person.name);//yue //*************************************** Person.prototype.name='su'; function Person(){ //隐式创建 // var this={ // __proto__:Person.prototype // } } var person =new Person(); // 改变原型 Person.prototype={ name:'yue' } console.log(person.name);//su var person1 =new Person(); console.log(person1.name);//yue
二、原型链
1.原型链上属性的修改
function Father(){ this.name='jing'; this.fortune={ 'card1':'100' } } var father=new Father(); Son.prototype=father; function Son(){ this.age=12; } var son=new Son(); // 引用值的修改 son.fortune.card1=200; console.log(father.fortune.card1);//200 son.fortune='10000'; console.log(father.fortune);//{card1: 200}
2.绝大多数对象的最终都会继承自Object.prototype
function Person(){ } var person=new Person(); console.log(person.__proto__==Person.prototype);//true console.log(Person.prototype.__proto__==Object.prototype);//true
3.Object.create(原型);
Object.create(null) 创建的对象是一个空对象,
在该对象上没有继承 Object.prototype 原型链上的属性或者方法,例如:toString(), hasOwnProperty()等方法
var test = Object.create({x:123,y:345}); console.log(test);//{} console.log(test.x);//123 console.log(test.__proto__.x);//123
三、call,apply 改变this指向,传参列表不同
// call 需要把实参按照形参的个数传进去
// apply 需要传一个数组 arguments
四、继承
1.传统形式-->原型链:过多的继承了没用的属性
2.借用构造函数(call,apply):不能继承借用构造函数的原型,每次构造函数都要多走一个函数
function Person(name,age){ this.name=name; this.age=age; } function Student(name,age,grade){ Person.call(this,name,age); this.grade=grade; } var student=new Student('asd',12,1);
3.共享原型:不能随便改动自己的原型
Father.prototype.name='haha'; function Father(){ } function Son(){ } function inherit(Target,Origin){ Target.prototype=Origin.prototype; } inherit(Son,Father);//Son.prototype=Father.prototype Son.prototype.age=12;//会改变father的原型 var son=new Son();// son.age=12 var father=new Father();//father.age=12
4.圣杯模式
// 继承方法 var inherit=(function(){ function F(){}; return function(Target,Origin){ F.prototype=Origin.prototype; Target.prototype=new F(); Target.prototype.constructor=Target;//构造函数指向自己 Target.prototype.uber=Origin.prototype;//记录继承的对象 } }()) Father.prototype.name='haha'; function Father(){ } function Son(){ } inherit(Son,Father); Son.prototype.age=21;//只改变son的原型 var son=new Son();// son.age=21 var father=new Father();//father.age=undefined