2016-11-17 137 views
0

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

+0

您将不得不使用'this'创建对当前对象的引用,并在更新中使用该新引用。因为'this'的作用域在函数内部发生了变化。所以你的驱动功能应该是这样的。 'drive:function(){var _self = this;函数update(){_ self.fuel - = 1;}} ...' –

+0

使用var that = this并使用内部更新函数 – Mahi

回答

-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();

希望它可以帮助

+0

它是* receiver *或* context *,而不是“scope”。而使用IIFE并不能解决任何问题,你的代码确实试图调用一个从未声明过的函数。 – Bergi

+0

好的,我不能通过iife发送这种情况,就像我做过 – Geeky

0

使用这样

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

+0

+的方式,非常感谢。 –

+0

@SaugatAwale很乐意帮忙 – Mahi