【发布时间】: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 3 是 true 而 point 4 是 false。此外,与第1点和2
不同,A点和B偏离正常顺序【问题讨论】:
-
table不是函数(并且不能被调用)。为什么你会期望它继承自Function.prototype?
标签: javascript constructor prototype