這是我的Java腳本代碼。訪問對象的屬性形成一個嵌套函數
var fiat = {
make: "Fiat",
model: "500",
year: 1957,
color: "Medium Blue",
passengers: 2,
convertible: false,
mileage: 88000,
fuel: 0,
started: false,
start: function() {
if (this.fuel == 0) {
console.log("The car is on empty, fill up before starting!");
} else {
this.started = true;
}
},
stop: function() {
this.started = false;
},
drive: function() {
function update(){
this.fuel-=-1;
}
if (this.started) {
if (this.fuel > 0) {
console.log(this.make + " " +
this.model + " goes zoom zoom!");
update();
} else {
console.log("Uh oh, out of fuel.");
this.stop();
}
} else {
console.log("You need to start the engine first.");
}
},
addFuel: function(amount) {
this.fuel = this.fuel + amount;
}
};
我想通過調用嵌套在屬性函數「drive」中的幫助器函數「update()」來更新燃料。我檢查了控制檯,似乎我不能訪問變量this.fuel屬性,因爲它打印「NaN」。
問題是如何從嵌套在「drive」屬性函數中的「update()」助手訪問對象屬性,以便我可以對「this.fuel」進行更改。謝謝。
您將不得不使用'this'創建對當前對象的引用,並在更新中使用該新引用。因爲'this'的作用域在函數內部發生了變化。所以你的驅動功能應該是這樣的。 'drive:function(){var _self = this;函數update(){_ self.fuel - = 1;}} ...' –
使用var that = this並使用內部更新函數 – Mahi