[英]Javascript Object to get this of parent method
In the following add
method of myObj
how can I get this
inside map? 在下面的myObj
add
方法中如何获取this
内部地图? In other words, this
when wrapped to map, points to that anonymous
function inside map. 换句话说, this
包裹到map时,指向map中的anonymous
函数。 How can I get this
there? 我怎么能在那里得到this
?
Note: Workarounds like creating a new variable
temp_sum
and adding and returning are not preferred. 注意:不建议使用创建新变量temp_sum
以及添加和返回的变通方法。 Because, I might have to do some tests inside them using the this keyword. 因为,我可能不得不使用this关键字在其中进行一些测试。
var myObj = {
sum : 0,
toAdd : [2,3,4],
add : function(){
this.toAdd.map(function(num){
this.sum += num //<-- How to get this.sum from here
})
return this.sum;
}
};
var m = Object.create(myObj);
var _sum = m.add();
document.getElementById("test").innerHTML = _sum;
You could use bind
你可以使用bind
var myObj = {
sum : 0,
toAdd : [2,3,4],
add : function(){
this.toAdd.map(function(num, index){
this.sum += num;
}.bind(this))
return this.sum;
}
};
or reduce
或reduce
var myObj = {
sum : 0,
toAdd : [2,3,4],
add : function(){
this.sum = this.toAdd.reduce(function(a,b){
return a + b;
});
return this.sum;
}
};
or a for
loop 或者一个for
循环
var myObj = {
sum : 0,
toAdd : [2,3,4],
add : function(){
for (var i=0; i<this.toAdd.length; i++) {
this.sum += this.toAdd[i];
}
return this.sum;
}
};
Array.prototype.map
method accepts optional argument: object value to be used as this
. Array.prototype.map
方法接受可选参数:要用作this
对象的对象值。 So your code will become as simple as: 所以你的代码将变得如此简单:
add: function () {
this.toAdd.map(function (num) {
this.sum += num;
}, this);
return this.sum;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.