这是我的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