2011-03-29 15 views
2

我一直在儘可能多地學習js在過去一週的繼承,並且遇到了john resig的簡單js繼承腳本。在測試代​​碼時,一切都很順利,直到我試圖遍歷我的一個擴展對象。下面的代碼:關於通過使用resig的簡單js繼承腳本創建的實例迭代的問題

var Person = Class.create({ 
    init : function(sex, devStage) { 
     this.sex = sex; 
     this.devStage = devStage || "newBorn"; 
    }, 
    Sex : function(val) { 
     if (val) { this.sex = val } 
     else { return this.sex; } 
    }, 
    DevStage : function(val) { 
     if (val) { this.devStage = val; } 
     else { return this.devStage; } 
    } 
}); 
var person = new Person("male"); 

var Mike = Person.extend({ 
    init : function(sex, devStage, name, age) { 
     this._super(sex, devStage); 
     this.name = name; 
     this.age = age; 
    }, 
    DevStage : function(val) { 
     if (val) { this._super(val); } 
     else { return this._super(); } 
    }, 
    Name : function(val) { 
     if (val) { this.name = val; } 
     else { return this.name; } 
    }, 
    Age : function(val) { 
     if (val) { this.age = val; } 
     else { return this.age; } 
    } 
}); 

var mike = new Mike("male", "adult", "Mike", 38); 

for (var k in mike) { 
    if (mike.hasOwnProperty(k)) { console.log("mike.hasOwnProperty(k) = " + k); } 
} //only "sex", "devStage", "name" and "age" show up as properties in firebug's console 

我期待「DevStage」,「名稱」和「時代」的功能特性的麥克風對象上存在,但它好像是唯一的屬性做它到每個對象的實例是那些被髮送到init函數。其他屬性在對象的原型上,並且工作正常,我只是無法使用hasOwnProperty方法找到它們。我讀過關於resig的博客文章的大部分評論,其中腳本發佈在哪裏,但我找不到與此問題有關的任何內容。

我的問題是這是否是正常的?如果在對象之間做一些屬性檢查,我可以看到時間這將是一個問題。這似乎是我的一個有效擔心?雖然不是全新的js,但我絕對不是經驗豐富的職業球員,所以任何有關我目前狀況的反饋都將非常感激。

回答

1

是的,這是正常的。屬性DevStageNameAgeinit附接到Mike原型,其中該新對象mike僅僅指向 - 當與new Mike()被創建對象的屬性不復制。

因此,mike沒有這些屬性「自己的屬性」 - 它們只能由看mike內部的原型屬性(這是JS引擎訪問屬性時,會自動執行:mike.DevStage)。一些JS引擎(例如Chrome)會將此內部原型屬性公開爲__proto__,您可以查看這些屬性。

這是mike內部是如何表示的描述:

mike = { 
    __proto__: { // Internal pointer to the prototype, for Mike 
     init: function() {}, 
     DevStage: function() {}, 
     Name: function() {}, 
     Age: function() {}, 
     __proto__: { // The prototype's prototype, for Person 
      init: function() {}, 
      Sex: function() {}, 
      DevStage: function() {} 

      // Ultimately, the prototype will point to Object.prototype 
      __proto__: {...} 
     } 
    }, 

    // Own properties 
    name: ..., 
    age: ..., 
    sex: ..., 
    devStage: ... 
} 

如果從環取出if (mike.hasOwnProperty(k))條件,那麼你會看到其它性能。

+0

哇......我想我從所有的學習中得到了一點點who = =)我完全忘記了從「新」呼叫返回的對象。在我的大部分代碼中,我使用的都是單例,所以它已經過了一段時間,因爲我已經用new來實例化了。非常感謝您對這個偉大解釋的快速回答! – mike 2011-03-29 06:54:00