我对理解一个方面有疑问。
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对象。并且汽车的位置不会增加。我的问题是如何从方法跳转到汽车对象上下文?
答案 0 :(得分:3)
您可以将父上下文保存到变量(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();