javascript 关于new()继承的笔记

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

使用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 //由①得来

 

转载于:https://www.cnblogs.com/zhaodawei/p/4322965.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值