访问对象的属性形成嵌套函数

时间:2016-11-17 19:21:16

标签: javascript javascript-objects

这是我的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()”帮助程序访问objects属性,以便我可以对“this.fuel”进行更改。感谢。

2 个答案:

答案 0 :(得分:0)

像这样使用

drive: function() {
        var that= this;
        function update(){
            that.fuel-=-1;
        }

答案 1 :(得分:-1)

是的,你不能在这里访问它,因为它已经失去了它的范围。你可以把它作为IIFE并发送给它

检查此代码段

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(obj) {
      obj.fuel -= -1;

    })(this);


    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;
  }
};
fiat.drive();

希望有所帮助

相关问题