2016.4.19—js继承(学习笔记)
2016-04-19 11:08
447 查看
1.继承的方式
对象冒充
这种方法可以支持多重继承,但存在一个弊端,如果实现多继承,可能出现超类中有相同的属性或者是方法,但最后的类具有优先级(覆盖前面的)。—>Function对象中加了两个新方法call()和apply().
call()方法
第一个参数用作this的对象,其他的参数直接传递给函数自身
apply()方法
apply()方法有两个参数,用作this的对象和要传递给函数的参数的数组。
上面两种方法都可以①的第二个参数是只有一个值的color的数组;②也可以吧ClassB的整个arguments对象作为第二个参数传递给apply()方法。
注意:只有超类中的参数顺序与子类的参数顺序完全一致时才可以传递参数对象,如不一致就要创建一个单独的数组,按正确的顺序放置参数。
原型链
子类的所有属性和方法都必须出现在prototype属性被赋值后,应为在它之前赋值的所有方法都被删除
混合方式
对象冒充
function ClassA(sColor){ this.color=sColor; this.sayColor=function(){ alert(this.color); }; } function ClassB(sColor){ this.newMethod=ClassA; this.newMethod=ClassA(sColor); delete this.newMethod; }
这种方法可以支持多重继承,但存在一个弊端,如果实现多继承,可能出现超类中有相同的属性或者是方法,但最后的类具有优先级(覆盖前面的)。—>Function对象中加了两个新方法call()和apply().
call()方法
第一个参数用作this的对象,其他的参数直接传递给函数自身
function ClassB(sColor,sName){ //this.newMethod=ClassA; //this.newMethod=ClassA(sColor); //delete this.newMethod; ClassA.call(this,sColor); //ClassA中的关键字this等于新创建的ClassB对象 this.name=sName; this.sayName=function(){ alert(this.name); } }
apply()方法
apply()方法有两个参数,用作this的对象和要传递给函数的参数的数组。
function ClassB(sColor,sName){ //this.newMethod=ClassA; //this.newMethod=ClassA(sColor); //delete this.newMethod; ClassA.apply(this,new Array(sColor)); ClassA.apply(this,arguments) this.name=sName; this.sayName=function(){ alert(this.name); } }
上面两种方法都可以①的第二个参数是只有一个值的color的数组;②也可以吧ClassB的整个arguments对象作为第二个参数传递给apply()方法。
注意:只有超类中的参数顺序与子类的参数顺序完全一致时才可以传递参数对象,如不一致就要创建一个单独的数组,按正确的顺序放置参数。
原型链
function ClassA{ } ClassA.prototype.color="red"; ClassA.prototype.sayColor=function(){ alert(this.color); } function ClassB{ } //在调用ClassA的构造函数时没有传递参数,在原型链中要确保构造函数中没有任何参数——>所以产生了混合方式 ClassB.prototype=new ClassA();
子类的所有属性和方法都必须出现在prototype属性被赋值后,应为在它之前赋值的所有方法都被删除
混合方式
function ClassA(sColor){ this.color=sColor; } ClassA.prototype.sayColor=function(){ alert(this.color); } function ClassB(sColor,sName){ ClassA.call(this,sColor); this.name=sName; } ClassB.prototype=new ClassA(); ClassB.prototype.sayName=function(){ alert(this.name); }
相关文章推荐
- JQuery1——基础($对象,选择器,对象转换)
- Android学习笔记(二九):嵌入浏览器
- Android java 与 javascript互访(相互调用)的方法例子
- JavaScript演示排序算法
- javascript实现10进制转为N进制数
- 最后一次说说闭包
- Ajax
- 2019年开发人员应该学习的8个JavaScript框架
- HTML中的script标签研究
- 对一个分号引发的错误研究
- 异步流程控制:7 行代码学会 co 模块
- ES6 走马观花(ECMAScript2015 新特性)
- JavaScript拆分字符串时产生空字符的原因
- Canvas 在高清屏下绘制图片变模糊的解决方法
- Redux系列02:一个炒鸡简单的react+redux例子
- JavaScript 各种遍历方式详解
- call/apply/bind 的理解与实例分享