如何更改对象 属性 的值

How to change value of the object's property

我对某一方面的理解有问题。

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

当我使用 this.loc++ 时,它指的是方法对象,而不是 Car 对象。并且汽车的位置没有增加。我的问题是如何从方法跳转到汽车对象上下文?

您可以将父上下文保存到变量 (var _this = 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();