5
考慮下面的代碼片段:爲什麼構造函數不是構造函數?
f = function() {};
f.prototype = {};
thing = new f;
我很驚訝地看到,thing.constructor
是Object()
。 (請參閱小提琴here。)
爲什麼不是thing.constructor
的功能f
?
考慮下面的代碼片段:爲什麼構造函數不是構造函數?
f = function() {};
f.prototype = {};
thing = new f;
我很驚訝地看到,thing.constructor
是Object()
。 (請參閱小提琴here。)
爲什麼不是thing.constructor
的功能f
?
因爲您已經用普通對象完全替換了f
的原始對象prototype
。這是原來的prototype
對象,通過.constructor
屬性舉行的參考f
。
一個對象的構造使用對象文本語法將是Object
構造函數創建。
把它找回來,你需要手動把它放在那裏。
f = function() {};
f.prototype = {};
f.prototype.constructor = f;
thing = new f;
這會影響新原型對象的原型鏈中的.constructor
屬性。
如果您刪除屬性,你會再次得到Object
。
delete f.prototype.constructor;
console.log(thing.constructor); // Object