【问题标题】:So this is saying i have an undefined variable in my fiat object?所以这是说我的法定对象中有一个未定义的变量?
【发布时间】:2016-04-21 03:07:55
【问题描述】:
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.started),但这也没有用。还有其他写法吗?

【问题讨论】:

标签: javascript oop object methods


【解决方案1】:

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

如果您想将其设为全局变量,请将var started; 添加到代码的开头。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-11
    • 2011-10-21
    • 1970-01-01
    • 2011-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多