2019独角兽企业重金招聘Python工程师标准>>>
//以下代码均摘自 Nicholas C.Zakas《Professional JavaScript for Web Developers》
//组合继承实例代码:
function SuperType(name) {
this.name = name;
this.colors = ["red", "blue", "green"];
}
SuperType.prototype.sayName = function() {
console.log(this.name);
};
function SubType(name, age) {
//通过call()调用SuperType的构造函数,继承SuperType属性
SuperType.call(this, name); //第二次调用SuperType()
this.age = age;
}
SubType.prototype = new SuperType();
SubType.prototype.sayAge = function() {
console.log(this.age);
};
var instancel = new SubType("Nicholas", 12); //第一次调用SuperType()
instancel.colors.push("black");
console.log(instancel.colors); //"red,blue,green,black"
instancel.sayName(); //"nicholas"
instancel.sayAge(); //12
var instancel2 = new SubType("Tom", 11);
console.log(instancel2.colors); //"red,blue,green"
instancel2.sayName(); //"Tom"
instancel2.sayAge(); //11
//原型式继承实例代码:
function createObj(o) {//对传入的对象执行了一次浅复制
function F() {}
F.prototype = o;
return new F();
}
var person = {
name: "Tom",
friends: ["one", "two", "van"]
};
var huPs = createObj(person);
huPs.name = "GRE";
huPs.friends.push("Rob");
var yePs = createObj(person);
yePs.name = "Lin";
yePs.friends.push("Sari");
console.log(person.friends);//"one,two,van,Rob,Sari"
/*
var huPs = Object.create(person);
var yePs = Object.create(person, {
name: {
value: "Greg"
}
});
第二个参数与Object.defineProperties()方法的第二个参数格式相同,每个属性都是通过自己
的描述符定义,以这种方式指定的任何属性都会覆盖原型对象上的同名属性
*/
/*
寄生组合式继承:通过借用构造函数来继承属性,通过原型链的混成形式来继承方法。不必为了指定子类型的原型而调用超类型的构造函数,我们所需要的无非就是超类型的原型的一个副本。使用寄生式继承来继承超类型的原型,然后将结果指定给子类型的原型
*/
//接收两个参数:子类型构造函数、超类型构造函数
function inheritPrototype(subType, superType) {
var prototype = object(superType.prototype); //创建对象 超类型原型副本
prototype.constructor = subType; //增强对象 为副本增添construct属性
subType.prototype = prototype; //指定对象
}
function SuperType(name) {
this.name = name;
this.colors = ["red", "blue", "green"];
}
SuperType.prototype.sayName = function() {
console.log(this.name);
};
function SubType(name, age) {
SuperType.call(this, name);
this.age = age;
}
inheritPrototype(SubType, SuperType);
SubType.prototype.sayAge = function() {
console.log(this.age);
};