你可能會尋找這樣的事情:
var customObject = function(){
this.title = "";
}
var setupMain = function(){ //"This" will point to instance, such as co
this.title = "initial setup value";
}
var co = new customObject();
co.setup = setupMain; //Reference to function
co.setup(); //Call the setup function
window.alert(co.title);
另外,如果你不希望有保留每段時間設定setup
函數來創建一個實例,你可以將它原型:
customObject.prototype.setup = setupMain; //Now, every customObject has a setup function
var co = new customObject();
co.setup();
window.alert(co.title);
最後,如果你不想有打電話setup();
每一次,你可以使用const內調用setup
ructor:
var customObject = function(){
this.setup(); //Call shared setupMain function because it's part of the prototype
}
var setupMain = function(){
this.title = "initial setup value";
}
customObject.prototype.setup = setupMain; //This can be shared across many prototypes
var co = new customObject();
window.alert(co.title);
'co.setup'未定義,因爲您調用了函數'setupMain',它沒有返回值。 – 2012-02-06 17:06:05
好的,那我該怎麼回來才能讓它分配函數,它的內容是co.setup?謝謝。 – 2012-02-06 17:10:29
在下面添加我的答案,讓我知道如果它不清楚。 – 2012-02-06 17:21:44