1.原型链继承(过多的继承无用的属性)
2.借用构造函数的方式继承
3.共享原型
function inherit(Target,Origin){
Target.prototype = Origin.prototype;
}
function Father() {}
Father.prototype.lastName = "Chen";
function Son() {}
inherit(Son, Father);
var son=new Son();
console.log(son.lastName);//Chen
Son.prototype.lastName="liu";
console.log(son.lastName);//liu
var f=new Father();
console.log(f.lastName);//liu
- 特点:当改造其中的一个构造函数的原型的时候,另一个构造函数的原型也受到影响。
4.圣杯模式
function inherit(Target, Origin) {
function F() {};//解决不同类型的构造函数之间污染的问题
F.prototype = Origin.prototype;
Target.prototype = new F();
Target.prototype.constructor = Target;//解决构造函数执行错误的问题
Target.prototype.uber = Origin.prototype;//z
}
function Father() {
}
Father.prototype.lastName = "Chen";
function Son() {
}
inherit(Son, Father);
var father = new Father();
var son = new Son();
Son.prototype.sex = "male";
console.log(son.sex); //male
console.log(father.sex); //undefined
console.log(son.constructor); //function Son(){...}
5.雅虎继承(闭包实现私有化属性)(推荐使用)
var inherit = (function (){
var F = function () {};
return function (Target, Origin){
F.prototype = Origin.prototype;
Target.prototype = new F();
Target.prototype.constructor = Target;
Target.prototype.uber = Origin.prototype;
}
}());
网友评论