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?

1

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.