javascript实现继承的几种方式
标签:
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. 输出:
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()方法
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦