所以这是说我的法定对象中有一个未定义的变量

So this is saying i have an undefined variable in my fiat object?

本文关键字:对象 有一个 未定义 变量 我的      更新时间:2023-09-26
var fiat = {
  make: fiat,
  model: "500",
  year: 1957,
  color: "medium Blue",
  passengers: 2,
  convertible: false,
  mileage: 88000,
  started: false,
  start: function() {
    started = true;
  },
  stop: function() {
    started = false;
  },
  drive: function() {
    if (started) {
      alert("Zoom Zoom!");
    } else {
      alert("Car needs to be started first.");
    }
  }
};
fiat.start();
fiat.drive();

所以它一直说一个变量没有定义。这就是我写在书中的方式。我也试着说,如果(fiat.start(,但这也没有用。还有其他方法可以写吗?

started是未定义的。这相当于写foo = "bar".通过使用var或将其附加到对象中的预定义started来定义它。

如果要使其成为全局变量,请将var started;添加到代码的开头。

在您的情况下,通过对象属性调用函数,将started替换为start()stop() this.started

相关文章: