您的位置:首页 > Web前端 > JavaScript

several way to implement inheritance in javascript

2013-05-14 23:45 399 查看
//1.prototype chain inheritance
function SuperType() {
this.property = true;
}
SuperType.prototype.getSuperValue = function () {
return this.property;
};
function SubType() {
this.subproperty = false;
}

//inherited from SuperType
SubType.prototype = new SuperType();
SubType.prototype.getSubValue = function () {
return this.subproperty;
};

//2.constructor stealing inheritance
function SuperType() {
this.colors = ["red","blue","green"];
}
function SubType() {
//inherited from SuperType
SuperType.call(this);
}

//3.combination inheritance
function SuperType(name) {
this.name = name;
this.colors = ["red", "blue", "green"];
}
SuperType.prototype.sayName = function () { alert(this.name); };
function SubType(name,age) {
//inherit properties
SuperType.call(this, name); //second call superType()
this.age = age;
}
//inherit method
SubType.prototype = new SuperType(); //first call superType()
SubType.prototype.sayAge = function () { alert(this.age); };

//4.prototypal inheritance in javascript
function object(o) {
function F() { }
F.prototype = o;
return new F();
}

//5.parasitic inheritance
function createAnother(original) {
var clone = object(original);
clone.sayHi = function () { alert("hi"); };
return clone;
}

//6.parasitic combinate inheritance
function inheritPrototype(subType, superType) {
var prototype = object(superType.prototype);
prototype.constructor = subType;
subType.prototype = prototype;
}
function SuperType(name) {
this.name = name;
this.colors = ["red","blue","green"];
}
SuperType.prototype.sayName = function () { alert(this.name); };

function SubType(name, age) {
SuperType.call(this, name);
this.age = age;
}
inheritPrototype(SubType,SuperType);
SubType.prototype.sayAge = function () { alert(this.age); };
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: