目录
本文介绍了继承模式逐步完善的过程,继承模式最终解决方案为--圣杯模式
构造函数A通过new生成a对象,使得A.prototype指向对象b,而对象b由构造函数B生成,这样就形成了原型链的继承关系
单一,所以实例都会继承到父类实例的属性
a.__proto__ --> A.prototype === b b.__proto__ --> B.prototype
Grand.prototype.lastName = 'Cheng';
function Grand() {
}
var grand = new Grand();
Father.prototype = grand;
function Father() {
this.name = 'ming';
}
var father = new Father();
Son.prototype = father;
function Son() {
}
var son = new Son();
console.log(son.lastName); // 'Cheng'
console.log(son.name); // 'ming'
通过call或者apply,在A的构造函数中执行调用B构造函数
执行了两次方法(缺点)
同原型链继承,过多的继承了无用的属性(缺点)
function Person(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
function Student (name, age, sex, grade) {
Person.call(this, name, age, sex);
this.grade = grade;
}
var student = new Student();
使得A.prototype = B.prototype
缺少个性化,如若想给A.prototype上面加自己的属性或方法,B.prototype也会加上
Father.prototype.lastName = 'cheng';
function Father() {
}
function son() {
}
// son.prototype = Father.prototype;
function inherit(Target, Origin) {
Target.prototype = Origin.prototype;
}
inherit(Son, Father);
var son = new Son();
console.log(son.lastName); // 'cheng'
共享原型和原型链组合的方式
参数接收的分别是要继承的构造函数和被继承的构造函数,之所以参数设定构造函数,是因为这样之后由改构造函数产生的对象都会被继承
// 接着共享原型改造 inherit
function inherit(Target, Origin) {
function F() {};
F.prototype = Origin.prototype;
Target.prototype = new F();
// 至此功能已经实现,下面是便利使用
Target.prototype.constuctor = Target; //由于继承了Origin,target的结构体变成了Origin的,所以要重新赋值
Target.prototype.uber = Origin.prototype; //设置uber 当想知道继承自谁时,直接调用即可
}
//雅虎精简版
var inherit = (function() {
var F = function() {};
return function(Target, Origin) {
F.prototype = Origin.prototype;
Target.prototype = new F();
Target.prototype.constuctor = Target;
Target.prototype.uber = Origin.prototype;
}
}());