为什么在对象中的函数中的 if 语句中需要 `this` 而不是在外部? JavaScript
Why `this` inside if statement in a function that is in an object is needed but not outside? JavaScript
代码如下所示
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
来告诉 JavaScript 我在想哪个 isStarted
。但是 car.start()
执行就像它知道它是来自对象的 isStarted
而不需要 this
关键字,除非
....
start: function() {
if(!isStarted) {
isStarted = true
}
}
....
isStarted
放在 if
里面,现在我需要 if (this.isStarted)
因为它会抛出 undefiend。
你需要在start
函数中解决this
,否则你创建了一个全局变量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();
代码如下所示
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
来告诉 JavaScript 我在想哪个 isStarted
。但是 car.start()
执行就像它知道它是来自对象的 isStarted
而不需要 this
关键字,除非
....
start: function() {
if(!isStarted) {
isStarted = true
}
}
....
isStarted
放在 if
里面,现在我需要 if (this.isStarted)
因为它会抛出 undefiend。
你需要在start
函数中解决this
,否则你创建了一个全局变量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();