PS:本文为《Javascript 高级程序设计》中继承中的学习笔记。
?JS继承方式
1.对象冒充
原理:构造函数使用了this关键字给所有属性和方法赋值(既采用类声明的构造函数方式)。因为构造函数只是一个函数,所以可使用ClassA的构造函数成为ClassB的方法,然后调用它。ClassB就会收到ClassA的构造函数中的属性和方法。
JavaScript代码
- function?ClassA(sColor){ ??
- ????this.color=sColor; ??
- ????this.sayColor=function(){ ??
- ????????alert(this.color); ??
- ????}; ??
- } ??
- function?ClassB(sColor,sName){ ??
- ????this.newMethod=ClassA; ??
- ????this.newMethod(sColor); ??
- ????delete?this.newMethod; ??
- ???? ??
- ????this.name=sName; ??
- ????this.sayName=function(){ ??
- ????????alert(this.name); ??
- ????}; ??
- } ??
- var?objA=new?ClassA(“red”); ??
- var?objB=new?ClassB(“blue”,“”); ??
- objA.sayColor(); ??
- objB.sayColor(); ??
- objB.sayName();??
?2.call()方法:
JavaScript代码
- function?sayColor(sa,ab){ ??
- ????alert(sa+this.color+this.age+ab); ??
- }; ??
- var?obj=new?Object; ??
- obj.color=“red”; ??
- obj.age=24; ??
- sayColor.call(obj,“aaaa”,“adadad”);??
?用call()可以改造,例如第一个例子:
?
JavaScript代码
- function?ClassA(sColor){???? ??
- ????this.color=sColor;???? ??
- ????this.sayColor=function(){???? ??
- ????????alert(this.color);???? ??
- ????};???? ??
- }???? ??
- function?ClassB(sColor,sName){???? ??
- ????//this.newMethod=ClassA;???? ??
- ????//this.newMethod(sColor);???? ??
- ????//delete?this.newMethod;?? ??
- ????ClassA.call(this,sColor); ??
- ???????? ??
- ????this.name=sName;???? ??
- ????this.sayName=function(){???? ??
- ????????alert(this.name);???? ??
- ????};???? ??
- }???? ??
- var?objA=new?ClassA(“red”);???? ??
- var?objB=new?ClassB(“blue”,“”);???? ??
- objA.sayColor();???? ??
- objB.sayColor();???? ??
- objB.sayName();???
最新评论
写的挺好的
有没有兴趣翻译 impatient js? https://exploringjs.com/impatient-js/index.html
Flexbox playground is so great!
感谢总结。
awesome!
这个好像很早就看到类似的文章了
比其他的教程好太多了
柯理化讲的好模糊…没懂