2011-06-20 113 views
0

的JavaScript訪問父對象我有這樣的汽車功能:內部功能

var Car = function(vendor, model, year) { 
    return { 
     vendor: vendor, 
     model: model, 
     year: year, 
     name: (function() { 
      return vendor + " " + model + " " + year; 
     })() 
    }; 
}; 
var foo = Car("Toyota","Corola",2007); 
alert(foo.name); //alerts "Toyota Corola 2007" 

這工作,但我想name能夠根據vendormodel,並year改變。

taxi.vendor = "Mitsubishi"; 
alert(taxi.vendor); //still alerts "Toyota Corola 2007" 

我怎麼能代替讓它根據vendor性質的變化提醒Mitsubishi Corola 2007

編輯:而漁獲-name必須保持一個屬性,不需要作爲一個函數調用。

+0

我有麻煩了,我沒有檢查之前的帖子! [酷之前討論] [1] [1]:http://stackoverflow.com/questions/6349121/choosing-an-oop-pattern-in-javascript –

回答

3

用的WebKit(Safari瀏覽器,Chrome瀏覽器)或Firefox的最新版本,您可以define getter and setter functions

var o = {a: 7, get b() {return this.a + 1;}, set c(x) {this.a = x/2}}; 
o.b // result is 8 
o.a = 10 
o.b // result is 11 

然後你可以這樣做:

var Car = function(vendor, model, year) { 
    return { 
     vendor: vendor, 
     model: model, 
     year: year, 
     get name() { return this.vendor + " " + this.model + " " + this.year; } 
    }; 
}; 

並得到你想要的結果。

我不知道IE或Opera是否支持這個版本或哪個版本。如果您需要支持其他什麼比最近的Safari瀏覽器,Chrome或Firefox瀏覽器,那麼你最好使用一個函數來訪問,而不是把它當作一個屬性名稱:

var Car = function(vendor, model, year) { 
    return { 
     vendor: vendor, 
     model: model, 
     year: year, 
     name: function() { return this.vendor + " " + this.model + " " + this.year; } 
    }; 
}; 

然後:

var foo = Car("Toyota","Corola",2007); 
alert(foo.name()); //alerts "Toyota Corola 2007" 
foo.vendor = "Mitsubishi"; 
alert(foo.name()); //alerts "Mitsubishi Corola 2007" 
2

如何:

var Car = function(thevendor, themodel, theyear) { 
    this.vendor = thevendor; 
    this.model = themodel, 
    this.year = theyear, 
    this.name = function() { 
      return this.vendor + " " + this.model + " " + this.year; 
     }; 
    return this; 
}; 


var foo = new Car("Toyota","Corola",2007); 
alert(foo.name()); //alerts "Toyota Corola 2007" 

foo.vendor = "Mitubishi"; 
alert(foo.name()); //alerts "Mistubishi Corola 2007" 

的jsfiddle此代碼:http://jsfiddle.net/duncan_m/gZKQD/

2

當您使用name: (function() {return vendor + " " + model + " " + year;})(),這意味着,name屬性將被設置爲執行此功能的結果。當您創建新的Car時會發生這種情況。但是,這聽起來像你想這個動態更新,所以考慮讓name是一個getter函數,而不是隻是一個字符串屬性:

name: function() {return vendor + " " + model + " " + year;}

然後,你可以做alert(taxi.name()),這將動態拼接的供應商,型號,和年份字符串。

+0

是否有可能不使'name'成爲一個函數? –

+0

如果你想在不使'name'成爲函數的情況下做到這一點,你必須設置setter函數(例如'setVendor','setModel'和'setYear'),以便每次改變時都可以重新創建'name' 。你也可以使用[getters and setters](https://developer.mozilla.org/en/Core_JavaScript_1。5_Guide/Working_with_Objects#Defining_Getters_and_Setters)作爲另一位評論者提到。 – jtbandes