今天就跟大家聊聊有关javascript中怎么实现继承,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。
对象冒充(多继承):
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. 输出:
blue red John
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. 输出:
blue red John
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. 输出:
blue red John
原型链(单继承):
a. 代码:
function ClassA(color) { this.color = color this.sayColor = function () { console.log(this.color); }; } function ClassB(name) { this.name = name this.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. 输出:
blue red John
混用对象冒充与原型链(多继承):
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. 输出:
blue red John
说明:
推荐使用call()方法或apply()方法
看完上述内容,你们对javascript中怎么实现继承有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。