理解call,this指针(用call实现继承),prototype模式实现继承的易错点
2011-10-09 14:57
344 查看
今天看别人写的博客看到有人说js实现继承刻用call实现,自己寡闻就看了下
摘自:http://ued.alimama.com/front-end/javascript-extend/ 叙述了所有实现继承的方式
摘自:http://ued.alimama.com/front-end/javascript-extend/ 叙述了所有实现继承的方式
function SuperType(name){ this.name=name; this.colors=["red","blue","green"]; } function SubType(){ SuperType.call(this); //继承了SuperType }一直不解。。知道自己写了个测试函数。。
<script> function superType(name){ this.color="re"; this.name=name; } var age=10; function subType(){ superType.call(this,"name"); //supertype函数的this为subType中的this,也就是说,subType中this指针称为superType的内部指针。。。 alert(this.age);//10 alert(this.color);//re } subType(); //var sub=new subType(); //alert(sub.color); //alert(sub.name); //alert(this.color); alert(this.age);//打印出10 alert(this.color);//re </script>
摘自:http://ued.alimama.com/front-end/javascript-extend/ 叙述了所有实现继承的方式
这种方式和subType(),这种方式是不一样的,,this指针指向的不同 上面的形式,this指针其实指向的是window对象。。 用注释的语句运行呢。。
<script> function superType(name){ this.color="re"; this.name=name; } var age=10; function subType(){ superType.call(this,"name");//supertype函数的this为subType中的this,也就是说,subType中this指针称为superType的内部指针。。。 alert(this.age);//undefinde alert(this.color);//re } //subType(); var sub=new subType(); //alert(sub.color); //alert(sub.name); //alert(this.color); alert(this.age);//10 alert(this.color);//undefined </script>
这时this就不再是全局的this指针了。。而是sub这个对象、、、 ---------------------------------------------------------- 下面讲一下 prototype的继承方式。。 如果”WD”的prototype对象,指向一个MED的实例,那么所有”WD”的实例,就能继承MED了。 如下实现
function MED(){ this.aim = "营销体验设计"; } function WD(){ this.skill = "java"; } WD.prototype=new MED(); WD.prototype.constructor = WD; //任何一个prototype对象都有一个constructor属性,指向它的构造函数。也就是 //说,WD.prototype 这个对象的constructor属性,是指向WD的。 //---------------------------- //这样就实现了继承 //-------------华丽的分割线----------- ///有人想直接赋值 WD.prototype = MED.prototype; WD.prototype.constructor = WD; //这样有什么问题呢?? //这样做的优点是效率比较高(不用执行和建立MED的实例了), //比较省内存。缺点是 WD.prototype和MED.prototype现在指向了同一个对象, //那么任何对WD.prototype的修改,都会反映到MED.prototype。
摘自:http://ued.alimama.com/front-end/javascript-extend/ 叙述了所有实现继承的方式
相关文章推荐
- Javascript:继续实现继承,支持:this.callParent(arguments)
- this上下文,以及通过call 、apply 实现继承
- 关于call ,this,继承,记录一点自己的初步理解
- javascript实现计数器理解this作用域
- C++中this指针的理解
- call(this)引起的对闭包的重新理解
- 编译器是如何用汇编语言实现C++的虚函数表和隐式传递this指针(三)
- javascript this 和 es6 箭头函数this 的理解以及call()、apply()、bind()的用法
- js定义对象的两种方法以及js用call来实现类的继承
- this指针与__thiscall调用方式
- Prototype和call(apply)结合实现继承
- this指针在普通函数、对象方法、定时器、构造函数、事件函数、call()、apply()中的执行
- javscript继承第二种实现call方法
- C++中关于this指针的理解
- this指针和类的继承 - C++快速入门16
- 深入理解JavaScript是如何实现继承的
- 图说js中的this——深入理解javascript中this指针
- this指针可以这样理解
- JavaScript 中的 this 用法以及 call(apply) 的理解
- javascript除call函数外实现继承的方式之一