代码看起来像这样
let car = {
make: "bmw",
model: "520",
isStarted: false,
start: function() {
isStarted = true
},
drive: function() {
if (isStarted) {
console.log("I am driving away....")
} else {
console.log("I am still false")
}
}
}
car.start();
car.drive();
我读到,因为它isStarted
是对象的一部分,所以我需要使用它this
来告诉JavaScriptisStarted
我正在考虑的对象。但是car.start()
执行时就像它知道它isStarted
来自对象一样,不需要this
关键字,除非
....
start: function() {
if(!isStarted) {
isStarted = true
}
}
....
isStarted
被放置在里面if
,现在我需要,if (this.isStarted)
因为它会抛出未防御状态。
您需要this
在start
函数中进行寻址,否则您将创建一个全局变量isStarted
。
let car = {
make: "bmw",
model: "520",
isStarted: false,
start: function() {
this.isStarted = true;
},
drive: function() {
if (this.isStarted) {
console.log("I am driving away....")
} else {
console.log("I am still false")
}
}
}
car.start();
car.drive();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句