例如:
function F() {};
F.prototype = {
test: function() { console.log('test'); }
};
console.log(F.prototype.constructor); // [Function: Object]
F.prototype = 'string';
var o = new F();
console.log(F.prototype.constructor); // [Function: String]
console.log(F.prototype); // string
console.log(o.constructor); // [Function: Object]
o.test(); // Can't work
在上面的代码中,初始构造函数是F()
,即F.prototype.constructor
。但随后我将 F.prototype
重置为 'string'
。还有我的问题:
- 将
F.prototype
重置为'string'
后,为什么F.prototype.constructor
变成了[Function: String]
。换句话说,它决定了F.prototype.constructor
? - 我知道新对象将继承
prototype
对象的属性,constructor
属性也是如此。但是为什么对象p
的构造函数是原来的构造函数[Function: Object]
,而不是[Function: String]
呢?
提前致谢。
最佳答案
constructor 字段没什么特别的,它和其他字段一样。
#1 的答案:
F.prototype = "string";
console.log(F.prototype.constructor); // function String
记录 function String
因为它和 一样
console.log("string".constructor); // function String
#2 的答案:
每个对象内部 __proto__
字段必须是 typeof x === "object"
。在原型(prototype)链的末尾总是有一个 null
值(通常是 Object.prototype.__proto__
一个),并且不允许循环。您将原始 string
分配给构造函数 prototype
字段 (typeof F.prototype === "string"
),它不能用作 __proto__
,所以 new
运算符只是返回使用默认原型(prototype)构造对象,即 Object.prototype
。
关于javascript - 重定义构造函数原型(prototype)后,对象构造函数指向原始构造函数而不是prototype.constructor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44435889/