2013-03-02 26 views
-1

我是約翰Resig的上構建一個系統的class inheritance implementation(JavaScript)的打印子類的名字,而不是「類」在使用約翰Resig的JavaScript類繼承的實現

一切運作良好,除了一個事實,即檢查/調試目的(也許對後來類型檢查,我想對實例化類的實際名稱的手柄

例如:下面從約翰的例子,返回Ninja代替Class

。我知道這個名字來自this.__proto__.constructor.name但這個道具是隻讀的。我想它必須是子類自身初始化的一部分。

有人嗎?

回答

0

如果你的代碼仔細觀察,你會看到這樣幾行:

Foo.prototype = new ParentClass;//makes subclass 
Foo.prototype.constructor = Foo; 

如果你省略第二行,要比構造函數名稱將是該父類。 名稱屬性很可能是隻讀的,但prototype不是,也不是原型的constructor屬性。這就是你如何設置「類」 /構造函數的名稱。

另請注意,__proto__不是獲取對象原型的方式。最好使用這個片段:

var protoOf = Object && Object.getPrototypeOf ? Object.getPrototypeOf(obj) : obj.prototype; 
//obviously followed by: 
console.log(protoOf.constructor.name); 
//or: 
protoOf.addProtoMethod = function(){};//it's an object, thus protoOf references it 
//or if all you're after is the constructor name of an instance: 
console.log(someInstance.constructor.name);//will check prototype automatically 

就這麼簡單,真的。

相關問題