【问题标题】:How to change value of the object's property如何更改对象属性的值
【发布时间】:2015-11-14 19:32:29
【问题描述】:

我在理解某一方面有问题。

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 对象。并且汽车的位置不会增加。我的问题是如何从方法跳转到汽车对象上下文?

【问题讨论】:

标签: javascript object object-oriented-analysis


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2019-03-09
    • 2018-07-31
    • 1970-01-01
    • 2018-12-31
    • 2023-03-08
    • 2021-11-23
    • 1970-01-01
    • 2016-01-09
    • 1970-01-01
    相关资源
    最近更新 更多