zoukankan      html  css  js  c++  java
  • js中的constructor 和prototype

    参考 http://www.cnblogs.com/yupeng/archive/2012/04/06/2435386.html

    function a(c){
        this.b = c;
        this.d =function(){
            alert(this.b);
        }
    }
    var obj = new a('test');
    console.log(obj.constructor);//a的function
    console.log(a);
    

    结果都是

    function a(c){
        this.b = c;
        this.d =function(){
            alert(this.b);
        }
    } 

    function 里面包含了

      1. argumentsnull
      2. callernull
      3. length0
      4. name""
      5. prototypeObject
      6. __proto__function Empty() {}
      7. <function scope>
    1. __proto__

    prototype 包含了2个属性,一个是constructor ,另外一个是__proto__

    一个实例化的对象他的__proto__指向的是原始对象的prototype,所以constructor也过来了。

    obj.constructor===a 是true,obj instanceof  a 也是true。如下面所示。

    可以这么说因为 obj.constructor===a 所以 obj instanceof  a 

    a {b: "test", d: function}
        b: "test"
        d: function (){
        __proto__: a
                constructor: function a(c){
                __proto__: Object                    
    

      

     总结下,一个实例化的对象的constructor === 它的没有实例化的对象。

     在arale源码里面调用父类方法,如下,他用到了constructor,this应该是实例化后的对象。this总是指向调用方法的对象,作为方法调用,那么this就是指实例化的对象。

        // The created class constructor 创建一个类的构造函数
        function SubClass() {
          // Call the parent constructor.
          parent.apply(this, arguments)
    
          // Only call initialize in self constructor.
          if (this.constructor === SubClass && this.initialize) {
            this.initialize.apply(this, arguments)
          }
        }
    

     参考下:http://www.2cto.com/kf/201407/313470.html

  • 相关阅读:
    区块链
    区块链
    区块链
    区块链
    区块链 – 介绍
    区块链 教程
    Matplotlib 直方图
    Matplotlib 饼图
    Matplotlib 柱状图
    Matplotlib 多个图形
  • 原文地址:https://www.cnblogs.com/danghuijian/p/3838371.html
Copyright © 2011-2022 走看看