2016-11-17 134 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