2012-07-23 75 views
3

我想在創建時使用其他對象傳遞參數來擴展一個新的JS對象。 此代碼不起作用,因爲我只能擴展沒有動態參數的對象。javascript動態原型

otherObject = function(id1){ 
    this.id = id1; 
}; 

otherObject.prototype.test =function(){ 
    alert(this.id); 
}; 

testObject = function(id2) { 
    this.id=id2; 
}; 

testObject.prototype = new otherObject("id2");/* id2 should be testObject this.id */ 


var a = new testObject("variable"); 
a.test(); 

有什麼建議嗎?

+0

使用你的調試器,並找到語法錯​​誤 – Bergi 2012-07-23 14:05:54

+0

閱讀:http://javascript.crockford.com/prototypal.html – rsplak 2012-07-23 14:06:12

+0

只需修復語法和引用錯誤,使其警告''變量''。不是很令人興奮 – Esailija 2012-07-23 14:08:12

回答

5

除了明顯的語法錯誤,繼承的正確JavaScript的方式是這樣的:

// constructors are named uppercase by convention 
function OtherObject(id1) { 
    this.id = id1; 
}; 
OtherObject.prototype.test = function() { 
    alert(this.id); 
}; 

function TestObject(id2) { 
    // call "super" constructor on this object: 
    OtherObject.call(this, id2); 
}; 
// create a prototype object inheriting from the other one 
TestObject.prototype = Object.create(OtherObject.prototype); 
// if you want them to be equal (share all methods), you can simply use 
TestObject.prototype = OtherObject.prototype; 


var a = new TestObject("variable"); 
a.test(); // alerts "variable" 

你會發現網上有很多關於這個的教程。

+0

第19行:未捕獲的JavaScript運行時異常:TypeError:在對象[object Object]中找不到函數測試 – user1497250 2012-07-23 15:58:04

+0

對不起,修正了一些錯別字;現在工作。 – Bergi 2012-07-23 16:20:54

+0

Works,但Eclipse JS無法看到類似object.protoype = new()的繼承。 – user1497250 2012-07-23 18:08:34

0

我不正是你想要什麼瞭解,但

otherObject.prototype.test = function() { 
    alert(this.id); 
}; 

是正確的。

而且這個

testObject.prototype = new otherObject(id2);

將不起作用,除非之前設置了id2。

請嘗試以下

var OtherObject = function() { 
    } 
    OtherObject.prototype.test = function() { 
     alert (this.id); 
    } 

    var TestObject = function (id) { 
     this.id = id; 
    } 
    TestObject.prototype = new OtherObject(); 

    var a = new TestObject("variable"); 
    a.test(); 
0

固定代碼

otherObject = function(id1){ 
    this.id = id1; 
}; 

otherObject.prototype.test =function(){ 
    alert(this.id); 
}; 

testObject = function(id2) { 
    this.id=id2; 
}; 

testObject.prototype = new otherObject("id2");/* id2 should be testObject this.id */ 


var a = new testObject("variable"); 
a.test(); 
0
testObject = function(id2) { 
    otherObject.call(this, id2); // run the parent object constructor with id2 parameter 
    this.id=id2; 
}; 

testObject.prototype = new otherObject(); // no id2 parameter here, it doesn't make sense 

注意的是,雖然創建的testObject一個實例中,otherObject的構造函數被調用兩次 - 一次創建原型,一旦初始化的對象。

爲了防止重複初始化,我們可以在我們僅使用它來創建原型時立即停止構造函數。

otherObject = function(id1){ 
    if (typeof id1 == 'undefined') { 
     /* as there is no parameter, this must be the call used to create 
     * the prototype. No initialisation needed here, we'll just return. 
     */ 
     return; 
    } 
    this.id = id1; 
}; 

P.S.請將大寫字母與對象一起使用。

+0

不要調用構造函數來創建原型對象! – Bergi 2012-07-23 14:12:38