首页 > 网站 > WEB开发 > 正文

javascript 关于new()继承的笔记

2024-04-27 14:12:15
字体:
来源:转载
供稿:网友

javascript 关于new()继承的笔记

2015-03-09 10:36 by zdwzdwzdw, ... 阅读, ... 评论, 收藏, 编辑

近期的一些学习总结,如有错误不严谨地方,希望指正!

使用new操作符会有如下操作:

1.创建一个对象temp = {},2. temp.__PRoto__ = A.prototype,3. A.call(temp, arguments),4. return temp.

    function a(name){        this.name="a";    }    function b(name){        this.name="b";    }    a.prototype.show=function(){        console.log("showaaaaa");    }    b.prototype.show=function(){        console.log("showbbbbb");    }

一:使用a = new b()的方式

    a=new b();    console.log(a);    console.log(a.prototype);    console.log(a.__proto__);    console.log(a.constructor);   a.show();    a.prototype.show();    

输出:

b {name: "b", show: function} // 使用a = new b()时相当于a原有的值被清空了,然后把b的this属性和原型属性赋给a,值和function都绑定在a的属性上undefined   //未定义a的prototype属性b {show: function} //a = new b()的方式a有一个隐藏属性__proto__指向b.prototypefunction b(name){ //同第一个        this.name="b";    } showbbbbb //同第一个Uncaught TypeError: Cannot read property 'show' of undefined //同第二个 

二:使用 a.prototype = new b()

    a.prototype=new b();    console.log(a);    console.log(a.prototype);    console.log(a.__proto__);    console.log(a.constructor);    // a.show();    a.prototype.show();    a.show();

输出:

function a(name){ //使用a.prototype=new b()时a原有的属性等未改变        this.name="a";    }  b {name: "b", show: function} // 但是a的prototype被b的this属性和原型属性完全覆盖了,所以a原有的prototype.show没有了function Empty() {} //a没有__proto__属性,a.prototype才有__proto__属性指向b.prototypefunction Function() { [native code] }  //重写了a.prototype所以a.constructor为空,需要再定义一次a的constructor指向showbbbbb  //同第二条Uncaught TypeError: undefined is not a function //a的没有show这个函数,a.prototype才有

三:a = new b()和a.prototype = new b()一起用

    a=new b();  ①    a.prototype=new b();  ②    console.log(a);    console.log(a.prototype);    console.log(a.__proto__);   console.log(a.prototype.__proto__);    console.log(a.constructor);     a.prototype.show();    a.show();

输出:

b {name: "b", prototype: b, show: function} //①里a被b的的this和原型属性覆盖,然后②里又给a添加了一个prototype属性b {name: "b", show: function} //②里被赋予了prototypeb {show: function} //a和a.prototype都有了一个__proto__属性b {show: function}function b(name){        this.name="b";    } showbbbbb  //由②得来showbbbbb  //由①得来


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表