Javascript 对象获取父方法的this
Javascript Object to get this of parent method
在myObj
下面的add
方法中,我怎样才能得到this
里面的地图?换句话说,this
当包装到 map 时,指向 map 中的那个 anonymous
函数。我怎样才能到达那里 this
?
Note: Workarounds like creating a new variable temp_sum
and adding
and returning are not preferred. Because, I might have to do some tests inside them using the this keyword.
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;
你可以使用 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;
}
};
或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;
}
};
或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
方法接受可选参数:要用作 this
的对象值。所以你的代码将变得如此简单:
add: function () {
this.toAdd.map(function (num) {
this.sum += num;
}, this);
return this.sum;
}
在myObj
下面的add
方法中,我怎样才能得到this
里面的地图?换句话说,this
当包装到 map 时,指向 map 中的那个 anonymous
函数。我怎样才能到达那里 this
?
Note: Workarounds like creating a new variable
temp_sum
and adding and returning are not preferred. Because, I might have to do some tests inside them using the this keyword.
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;
你可以使用 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;
}
};
或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;
}
};
或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
方法接受可选参数:要用作 this
的对象值。所以你的代码将变得如此简单:
add: function () {
this.toAdd.map(function (num) {
this.sum += num;
}, this);
return this.sum;
}