javascript - Accesing the object's property form a nested function -


this question has answer here:

here java script code.

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 on empty, fill 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 start engine first.");         }     },      addfuel: function(amount) {         this.fuel = this.fuel + amount;     } }; 

i want update fuel invoking helper function "update()" nested inside property function "drive". checked in console seems can't access variables this.fuel property since prints "nan".

the question how access objects property "update()" helper nested inside "drive" property function can make changes "this.fuel". thanks.

use this

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


Comments

Popular posts from this blog

java - inputmismatch exception -

c - zlib and gdi32 with OpenSSL? -

Formatting string according to pattern without regex in php -