打好基础,查漏补缺
基础是重中之重
继承的发展史
1、原型链继承
子构造函数的原型等于父级构造的对象
过多的继承了无用的属性。
Person.prototype.lastName = 'Keung'
function Person(name,age){
this.name = name
this.age = age
this.say = function (){
console.log(this.say)
}
}
var person = new Person('To',24)
Student.prototype = person
function Student(name,age){
}
var student = new Student('To',24)
2、构造函数继承
使用call或apply借用其他构造函数
Person.prototype.lastName = 'Keung'
function Person(name,age){
this.name = name
this.age = age
this.say = function (){
console.log(this.say)
}
}
var person = new Person('To',24)
Student.prototype = person
function Student(name,age,grade){
Person.call(this,name,age)
this.grade = grade
}
var student = new Student('To',24,100)
无法继承借用函数的原型链
每次构造函数都要多调用一次函数
3、共享继承
子构造函数想在自己原型上增加一个属性,那么父类构造函数原型上也会增加。所以用第四种方法。
Person.prototype.lastName = 'Keung'
function Person(name,age){
}
var person = new Person('To',24)
Student.prototype = Person.prototype
function Student(name,age,grade){
}
var student = new Student('To',24,100)
4、圣杯模式
防止原型链上的相互影响,但是如果直接改变原型链上原有的属性,还是会因为引用值的问题改变父级构造函数的原型。
利用立即执行函数和闭包 ,实现变量私有化
var inherit = (function(){
function F(){}
return function (target,orign){
F.prototype = orign.prototype
target.prototype = new F()
target.constructor = target // 否则target的constructor 会指向orign
target.uber = orign.prototype // 标注target 继承自谁
}
}())