【问题标题】:Confused by javascript's constructor and prototype?对 javascript 的构造函数和原型感到困惑?
【发布时间】:2011-07-19 03:29:38
【问题描述】:
function MyObject(){}
Array.prototype={};
MyObject.prototype={};
var a=new Array();
var b=new MyObject();
alert(a.constructor==Array);//true
alert(b.constructor==MyObject);//false

【问题讨论】:

标签: javascript constructor prototype-programming


【解决方案1】:

Array.prototype 是不可写属性。

因此,您的任务:

Array.prototype = {}

...没有成功,所以它的.constructor 属性没有改变。

15.4.3.1 Array.prototype

Array.prototype的初始值为Array原型对象(15.4.4)。

此属性具有属性{ [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }

...而使用您的自定义构造函数,您可以分配不同的原型对象,因此您已经覆盖了通过.constructor 引用构造函数的原始对象。

【讨论】:

    【解决方案2】:

    constructor 属性在您使用自己的空对象实例覆盖 prototype 属性时被覆盖,因为 ({}).constructor === Object。你可以做任何一个

    function MyObject() {}
    MyObject.prototype = {};
    MyObject.prototype.constructor = MyObject;
    

    或者(更好的 IMO)你不能直接设置 prototype,而是增加它:

    function MyObject() {}
    MyObject.prototype.foo = "bar";
    

    还要注意:Array.prototype 不可写,因此您的行 Array.prototype = {} 将静默失败(或在严格模式下大声失败)。

    【讨论】:

      【解决方案3】:
      > function MyObject(){} 
      > Array.prototype={};
      

      你不能给 Array.prototype 赋值。

      > MyObject.prototype={};
      > var a=new Array();
      > var b=new MyObject();
      > alert(a.constructor==Array);//true
      

      Array.prototype 具有引用 Array 函数的 constructor 属性。由于a是Array的一个实例,它继承了Array.prototype的constructor属性。

      > alert(b.constructor==MyObject);//false
      

      您已为 MyObject.prototype 分配了一个空对象,它没有 prototype 属性,b 也没有。

      MyObject.prototype.constructor = MyObject;
      
      alert(b.constructor==MyObject); // true
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-05-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-12
        相关资源
        最近更新 更多