gpt4 book ai didi

Javascript对象获取父方法的this

转载 作者:行者123 更新时间:2023-11-29 10:40:58 25 4
gpt4 key购买 nike

myObj 的以下 add 方法中,如何在 map 中获取 this ?换句话说,this 当包装到 map 时,指向 map 中的那个 anonymous 函数。我怎样才能得到 this 呢?

Note: Workarounds like creating a new variable temp_sumand 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;
}
};

减少

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;
}
};

关于Javascript对象获取父方法的this,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29449262/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com