代码改变世界

javascript 关于new()继承的笔记

2015-03-09 10:36  zdwzdwzdw  阅读(291)  评论(0编辑  收藏  举报

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

使用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.prototype
function 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.prototype
function 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} //②里被赋予了prototype
b {show: function} //a和a.prototype都有了一个__proto__属性
b {show: function}
function b(name){ this.name="b"; } showbbbbb //由②得来 showbbbbb //由①得来