获取此父方法的Javascript对象
在下面的获取此父方法的Javascript对象,javascript,javascript-objects,Javascript,Javascript Objects,在下面的addmethod ofmyObj中,如何获取此内部地图?换句话说,this包装到map时,指向map中的匿名函数。我怎样才能在那里得到这个 注意:解决方法包括创建新变量temp\u sum和添加 而且不喜欢返回。因为,我可能必须使用this关键字在它们内部进行一些测试 var myObj={ 总数:0,, toAdd:[2,3,4], 添加:函数(){ this.toAdd.map(函数(num){ this.sum+=num/您可以使用bind var myObj = {
add
method ofmyObj
中,如何获取此
内部地图?换句话说,this
包装到map时,指向map中的匿名
函数。我怎样才能在那里得到这个
注意:解决方法包括创建新变量temp\u sum
和添加
而且不喜欢返回。因为,我可能必须使用this关键字在它们内部进行一些测试
var myObj={
总数:0,,
toAdd:[2,3,4],
添加:函数(){
this.toAdd.map(函数(num){
this.sum+=num/您可以使用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;
}
};
或用于
循环的
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;
}
};
var myObj={
总数:0,,
toAdd:[2,3,4],
添加:函数(){
for(var i=0;i方法接受可选参数:对象值用作this
。因此,您的代码将变得非常简单:
add: function () {
this.toAdd.map(function (num) {
this.sum += num;
}, this);
return this.sum;
}
为什么不使用for
loop?@Vld,只是在map周围工作,因为它看起来很干净。看起来应该用于for loop。非常好。还有一件事。它不是必需的,但是可以在map内获得项的索引吗?是的,map
有三个内置参数,它们是map(currentValue,Index,array)
add: function () {
this.toAdd.map(function (num) {
this.sum += num;
}, this);
return this.sum;
}