[英]How to change value of the object's property
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. 当我使用this.loc ++时,它指的是方法对象,而不是Car对象。 And location of car is not incremented. 并且汽车的位置不会增加。 My question is how to jump to car object context from methods? 我的问题是如何从方法跳转到汽车对象上下文?
You can save parent context to variable ( var _this = this;
), like this 您可以将父上下文保存到变量( 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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.