1

I have problem with understanding one aspect.

var Car = function(name, loc) {
    'use strict';
    this.name = name;
    this.loc = loc;
    this.methods = {
        move: function() {
           this.loc++;
        },
        show: function() {      
            console.log('Position of ' + this.name + ' is: ' + this.loc);
        }
    };
};
var amy = new Car('amy', 1);
var ben = new Car('ben', 9);

When I use this.loc++ it's referring to methods object, not to Car object. And location of car is not incremented. My question is how to jump to car object context from methods?

Steave
  • 137
  • 1
  • 2
  • 8
  • See http://stackoverflow.com/questions/4886632/what-does-var-that-this-mean-in-javascript – joews Nov 14 '15 at 19:36

1 Answers1

3

You can save parent context to variable (var _this = this;), like this

var Car = function(name, loc) {
    'use strict';
    var _this = this;
  
    this.name = name;
    this.loc = loc;
    this.methods = {
        move: function() {
           _this.loc++;
        },
        show: function() {      
            console.log('Position of ' + _this.name + ' is: ' + _this.loc);
        }
    };
};

var amy = new Car('amy', 1);
var ben = new Car('ben', 9);

amy.methods.move();
amy.methods.move();
amy.methods.show();
Oleksandr T.
  • 76,493
  • 17
  • 173
  • 144