我找不到JS spec中的任何地方,其中功能 - 當用new
調用時,應該將其原型的constructor
屬性設置爲自己。不是spec中的構造函數的JavaScript prototype.constructor屬性?
確保規範說的內置構造函數(對象,數組,字符串,& c)所有設置其屬性prototype.constructor
自己(即Object.prototype.constructor = Object
),但我找不到任何地方,說這必須/應該發生的其他構造函數(似乎應該在[[Construct]]
部分(13.2.2 [[Construct]]
拼寫出來),但它不是:
function F() {};
var obj = new F();
Object.getPrototypeOf(obj).constructor == F; // non-standard?? I can't find where in spec
我問,因爲我看到很多代碼「復位」構造的prototype.constructor財產'返回'本身 - 但這似乎是非標準的,這個屬性指出了構造函數的第一位?
function F() {};
F.prototype = new Parent();
F.prototype.constructor = F; // 'reset' it cuz it changed! (according to spec it should never have been set? Except in Object.prototype.
能/應該JS程序員依靠這種非標準(?)期望構造的prototype.constructor屬性將重新指向構造函數本身如果原型屬性沒有設置?
V8肯定不會這樣的:
function F() {};
console.log(F.prototype.constructor === F); // true! WHY??? not in spec? Should be Object?
。希望取得隱隱約約地感覺到 - 謝謝! Mark
PS由於它們的可變性,我只能依靠instanceof
而不是使用constructor
屬性。
我認爲最好的做法是產品總數開溝構造和使用的Object.create和.isPrototypeOf。 – Alex
你說得對,'[[construct]]'('new'關鍵字)不會設置構造函數屬性。相反,它是從使用該函數創建的默認原型對象繼承的,請參見[section 13.2](http://es5.github.com/#x13.2) – Bergi
dun thanks〜!!!不知道我怎麼錯過了...... – user1883202