这里我有一个程序,可以计算一个人不同的日常事件,例如他一周踢足球的次数等。这里我有一个 switch 语句,可以计算不同事件的值。我强制这个对象指示
。但是在 sort()
函数内的 dayEvents 对象forEach 方法
内,它指示全局对象。还有一个错误,说足球未定义。为什么是是这样吗?我不知道如何强制它指示相同的 dayEvents
对象??
<html>
<body>
<script>
(function(){
var dayEvents={
football:0,
school:0,
video_games:0,
watch_tv:0,
coding:0,
container:[],
insert:function(evt){
this.container.push(evt);
},
get:function(){
sort.call(this);
}
}
function sort(){
for(i=0;i<this.container.length;i++){
this.container[i].forEach(function(elements,index,array){
switch(elements){
case football:
(this.football)++;
break;
case school:
(this.school)++;
break;
case video_games:
(this.video_games)++;
break;
case watch_tv:
(this.watch_tv)++;
break;
case coding:
(this.coding)++;
break;
}
});
}
}
dayEvents.insert(['football','school','video_games','watch_tv','coding']);
dayEvents.insert(['football','school','coding']);
dayEvents.insert(['school','video_games','watch_tv','coding']);
dayEvents.insert(['football','video_games','coding']);
dayEvents.insert(['school','watch_tv','coding']);
dayEvents.insert(['football','school','video_games','watch_tv','coding']);
dayEvents.insert(['football','school','video_games','coding']);
dayEvents.get();
console.log(dayEvents.football);
})();
</script>
</body>
</html>
最佳答案
向forEach
提供第二个参数,称为thisArg
;它会在迭代器回调期间将其用作 this
。
我认为您正在寻找与外部相同的迭代器内部调用,因此:
this.container[i].forEach(function(elements,index,array){
/* ...contents omitted for brevity... */
}, this);
// ^^^^^^
或者,您可以通过 Function#bind
使用绑定(bind)函数,但由于 forEach
专门为您提供 thisArg
,这可能是去。 (所有其他 ES5 数组添加也都有它,仅供引用 - some
、every
、reduce
,...)
另外,正如乔治在对该问题的评论中指出的那样,您的 case
标签的值有点可疑:
case football:
如果你有一个名为 football
的变量(这可能会让一些人感到惊讶!),那么这在 JavaScript 中是有效的,但是看看你的代码,我怀疑你可能想要:
case "football":
...其他人也类似。
关于javascript - 强制 this 指示 forEach 语句中所需的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25722832/