【问题标题】:Why JavaScript construction function default prototype is Object.Prototype instead of Function.prototype?为什么 JavaScript 构造函数的默认原型是 Object.Prototype 而不是 Function.prototype?
【发布时间】:2021-11-06 11:14:37
【问题描述】:

函数对象 被用作构造函数时,正确的原型链将被维护,如第 1 点和第 2 点中标记的那样。

但如以下代码所示,新实例原型正在跳过 Function.prototype 并直接从 Object.prototype 继承。有什么具体原因吗?

Function.prototype.extraFun = function(){console.log('funny function')};

function Thing(name){
    this.name = name;
}

Thing.prototype.specs = function(){
    return `name: ${this.name}`;
}

var table = new Thing('wooden table');

table.__proto__ == Thing.prototype //true       [OK]            (1)
Thing.__proto__ == Function.prototype //true    [OK]            (2)  

//it should show follow the above rythm
Function.__proto__ == Object.prototype //false               (A)

//why 
Function.__proto__ == Object.__proto__ //true                (B)

//it should be false
table.__proto__.__proto__ == Object.prototype // true             (3)  

//it should be true because function object is instance of Function NOT Object directly
table.__proto__.__proto__ == Function.prototype //false            (4)

但问题是为什么 point 3truepoint 4false。此外,与第1点2

不同,A点B偏离正常顺序

【问题讨论】:

  • table 不是函数(并且不能被调用)。为什么你会期望它继承自Function.prototype

标签: javascript constructor prototype


【解决方案1】:
table.__proto__ == Thing.prototype //true       [OK]            (1)
Thing.__proto__ == Function.prototype //true    [OK]            (2)  

//it should show follow the above rythm
Function.__proto__ == Object.prototype //false               (A)

//why 
Function.__proto__ == Object.__proto__ //true                (B)

不是真的。 table 是奇怪的。节奏是这样的:

Thing.__proto__ == Function.prototype //true    [OK]
Function.__proto__ == Function.prototype //true [OK]
Object.__proto__ == Function.prototype //true   [OK]

你能看出它们的共同点吗?它们是构造函数。

table.__proto__ == Thing.prototype //true       [OK]            (1)
Thing.__proto__ == Function.prototype //true    [OK]            (2) 
table.__proto__.__proto__ == Object.prototype // should be false but is true?
table.__proto__.__proto__ == Function.prototype // should be true but is false?

不,table 的原型链中不涉及函数对象(将是Function 的实例,并继承自Function.prototype)。你似乎认为Thing.prototypeThing.__proto__ 是同一个东西——但是no, they're absolutely not

继承链简单

           table.__proto__ == Thing.prototype
 Thing.prototype.__proto__ == Object.prototype
Object.prototype.__proto__ == null

【讨论】:

    【解决方案2】:

    构造函数(ThingFunctionObject)是函数,所以它们的原型链中有Function.prototype

    Function.prototypeThing.prototype 继承自 Object.prototype

    这些线代表.__proto__ 依赖项(向上)。

    请参阅How does JavaScript prototype work?,我也在其中发布了an answer

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-27
      • 1970-01-01
      • 2017-12-09
      • 1970-01-01
      • 2020-05-08
      • 2011-01-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多