prototype and constructor object properties

前端 未结 4 1727
孤城傲影
孤城傲影 2020-12-04 14:48

I\'ve:

function Obj1(param)
{
    this.test1 = param || 1;

}

function Obj2(param, par)
{
    this.test2 = param;

}

now when I do:

<
4条回答
  •  -上瘾入骨i
    2020-12-04 15:34

    Well, the constructor property is a property like any other, on the prototype (property) of Obj1. If you understand how prototypes work, this might help:

    >>> obj.hasOwnProperty("constructor")
    false
    
    // obj's [[Prototype]] is Obj2.prototype
    >>> Obj2.prototype.hasOwnProperty("constructor")
    false
    
    // Obj2.prototype's [[Prototype]] is Obj1.prototype
    >>> Obj1.prototype.hasOwnProperty("constructor")
    true
    
    // Oh?
    >>> Obj1.prototype.constructor
    Obj1()
    

    Aha! So obj has no constructor, JS goes to get it up the [[Prototype]] chain, all the way from Obj1.prototype.constructor

    I'm not sure why the constructor property isn't just set on an object when you use `new'. There might be a reason, or it might just be an oversight. Either way, I tend to avoid it.

提交回复
热议问题