Js各种继承方法总结
来源:互联网 发布:mysql 创建触发器 编辑:程序博客网 时间:2024/04/30 22:29
//原型链方式 function ClassA() { } ClassA.prototype.color = "red"; ClassA.prototype.sayColor = function () { console.log(this.color); } function ClassB() {} ClassB.prototype = new ClassA(); var b = new ClassB(); console.log(b.sayColor());
//call方法继承 function ClassA(sColor, sName) { this.sColor = sColor; this.sName = sName; this.sayColor = function () { console.log(this.sColor); } } function ClassB(sColor, sName, type) { ClassA.call(this, sColor, sName); this.type = type; this.show = function () { console.log(this.sColor + " " + this.sName + " " + this.type); } } var b = new ClassB("red", "color_1", "color"); console.log(b.sayColor()); console.log(b.show());call方法,即调用一个对象的一个方法,以另一个对象替换当前对象。
在我打的这个例子中,可以看做ClassA对象代替this对象在ClassB中执行,那么就实现了ClassB对ClassA的继承。
//apply方法继承 function ClassA(sColor, sName) { this.sColor = sColor; this.sName = sName; this.sayColor = function () { console.log(this.sColor); } } function ClassC(sColor, sName, type) { this.type = type; ClassA.apply(this, arguments); this.show = function () { console.log(this.sColor + " " + this.sName + " " + this.type); } } var c = new ClassC("blue", "color_2", "color"); console.log(c.sayColor()); console.log(b.show());apply方法的作用与call方法类似,只是第二个参数不一样,传入的第二个参数是一个数组。
//对象冒充 function ClassA(sColor) { this.sColor = sColor; this.sayColor = function () { console.log(this.sColor); } } function ClassB(sColor, sName) { //把ClassB看作构造函数 this.method = ClassA; //定义成员方法,把函数ClassA作为成员方法 this.method(sColor); //执行成员方法,相当于new一个ClassA delete this.method; this.sName = sName; this.show = function () { console.log(this.sColor + " " + this.sName); } } var b = new ClassB("white", "color_3"); console.log(b.sayColor()); console.log(b.show());事实上call和apply也是像这种一样的对象冒充继承方法
//混合方式 function ClassA(sColor) { this.sColor = sColor; } ClassA.prototype.sayColor = function () { console.log(this.sColor); } function ClassB(sColor, name) { ClassA.call(this, sColor); this.name = name; } ClassB.prototype = new ClassA(); ClassB.prototype.show=function(){ console.log(this.sColor+" "+this.name); } var b = new ClassB("black", "color_4"); console.log(b.sayColor()); console.log(b.show());利用call和原型链的混合方式,应该是比较合理的方式了,对象的属性要么来自自身属性,要么来自prototype,
在混合方式中,用call方式继承父类函数的属性,用原型链方式继承父类prototype对象的方法
0 0
- Js各种继承方法总结
- js继承方法的总结
- JS继承的几种方法总结
- js实现继承的各种方法及缺点
- js中的各种继承方式
- js中实现继承6种方法总结
- js继承方式总结
- JS中的继承总结
- 继承中的各种方法研究
- js各种基础总结
- JS的继承方法
- js常用继承方法
- JS对象继承方法
- js继承方法
- 各种js方法
- JavaScript继承方法总结
- 各种排序方法总结
- 各种排序方法总结
- 小珂的游戏
- JAVA设计模式之策略模式
- 南邮-2047(地铁换线)
- anagrams两种解法 用map来优化查找
- 实验二
- Js各种继承方法总结
- poj3264
- quick-cocos2d-x3.2 scheduler使用注意事项
- 领会
- 主页导航设计
- Fedora20 kermit串口工具
- C语言上机
- 考试冲刺期--软件设计师
- java中枚举类型enum的使用和分析