zoukankan      html  css  js  c++  java
  • 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 //由①得来
  • 相关阅读:
    通过API方式查看Azure Sign-ins记录
    定期删除Azure存储账号下N天之前的数据文件-ASM
    定期删除Azure存储账号下N天之前的数据文件-ARM
    使用自定义映像批量创建托管磁盘虚拟机
    CentOS6.9 ARM虚拟机扩容系统磁盘
    Linux小技巧
    mysql数据导到本地
    mac安装pkg 一直“正在验证” 卡着
    idea compare功能 之一次bug修复
    番茄三月账单
  • 原文地址:https://www.cnblogs.com/zhaodawei/p/4322965.html
Copyright © 2011-2022 走看看