Javascript 重新定义构造函数函数的原型后,对象构造函数指向原始构造函数而不是prototype.constructor
例如:Javascript 重新定义构造函数函数的原型后,对象构造函数指向原始构造函数而不是prototype.constructor,javascript,oop,constructor,prototype,Javascript,Oop,Constructor,Prototype,例如: 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]
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
变为[函数:string]
。换句话说,它决定了
F.prototype.constructor
李>
prototype
对象的属性,constructor
属性也是如此。但是为什么对象p
的构造函数是原始构造函数[函数:对象]
,而不是[函数:字符串]
李>
提前感谢。构造函数字段没有什么特别的,它和其他字段一样 回答#1:
F.prototype = "string";
console.log(F.prototype.constructor); // function String
记录函数字符串
,因为它与
console.log("string".constructor); // function String
回答#2:
F.prototype = "string";
console.log(F.prototype.constructor); // function String
每个对象内部
\uuuu proto\uuuu
字段必须是typeof x==“object”
。在原型链的末尾总是有一个null
值(通常是对象.prototype.\uuuuu proto\uuuu
一个),并且不允许循环。您为构造函数prototype
字段(typeof F.prototype==“string”
)分配了一个原语string
),该原语不能用作\uuuuuuuuu
,因此新的
操作符只需返回到使用默认原形构建对象,即对象。prototype
确定,@Liam>。谢谢你的建议。回答得好!谢谢我想知道是否有任何方法可以打印构造函数的源代码,而不仅仅是它的类型[函数:Object]
?@zhenguoliconstructor.toString()
@Bergi,好的,我知道。