对象冒充(多继承):
a. 代码:function ClassA(sColor) {this.color = sColor;this.sayColor = function () { console.log(this.color);};}function ClassB(sName) {this.name = sName;this.sayName = function () { console.log(this.name);};}function ClassC(sColor, sName) {this.newMethod = ClassA;this.newMethod(sColor);delete this.newMethod;this.newMethod = ClassB;this.newMethod(sName);delete this.newMethod;}var objA = new ClassA("blue");var objC = new ClassC("red", "John");objA.sayColor();objC.sayColor();objC.sayName();
b. 输出:
blueredJohn
call()方法(推荐):
a. 代码:function ClassA(sColor) {this.color = sColor;this.sayColor = function () { console.log(this.color);};}function ClassB(sName) {this.name = sName;this.sayName = function () { console.log(this.name);};}function ClassC(sColor, sName) {ClassA.call(this,sColor)ClassB.call(this,sName)}var objA = new ClassA("blue");var objC = new ClassC("red", "John");objA.sayColor();objC.sayColor();objC.sayName();
b. 输出:
blueredJohn
apply()方法(推荐):
a. 代码:function ClassA(sColor) {this.color = sColor;this.sayColor = function () { console.log(this.color);};}function ClassB(sName) {this.name = sName;this.sayName = function () { console.log(this.name);};}function ClassC(sColor, sName) {ClassA.apply(this,new Array(sColor))ClassB.apply(this,new Array(sName))}var objA = new ClassA("blue");var objC = new ClassC("red", "John");objA.sayColor();objC.sayColor();objC.sayName();
b. 输出:
blueredJohn
原型链(单继承):
a. 代码:function ClassA(color) {this.color = colorthis.sayColor = function () { console.log(this.color);};}function ClassB(name) {this.name = namethis.sayName = function () { console.log(this.name);};}ClassB.prototype = new ClassA("red");var objA = new ClassA("blue");var objB = new ClassB("John");objA.sayColor();objB.sayColor();objB.sayName();
b. 输出:
blueredJohn
混用对象冒充与原型链(多继承):
a. 代码:function ClassA(sColor) {this.color = sColor;this.sayColor = function(){ console.log(this.color)}}function ClassB(sName) {this.name = sName;this.sayName = function(){ console.log(this.name)}}function ClassC(sColor, sName) {ClassA.call(this, sColor);ClassB.call(this, sName);}ClassC.prototype = new ClassA();ClassC.prototype = new ClassB();var objA = new ClassA("blue");var objC = new ClassC("red", "John");objA.sayColor();objC.sayColor();objC.sayName();
b. 输出:
blueredJohn
说明:
推荐使用call()方法或apply()方法