为什么第7行返回对象window?
为什么不是运动对象?
var sport = {
caption: "2017",
players : [{"name":"cat"},{"name":"dog"}] ,
show: function() {
this.players.forEach(function(entry) {
console.log(entry.name);
console.log(this);//window
});
}
}
sport.show();
最佳答案
this
指的是它所在的匿名函数的作用域,即 window。
var sport = {
players: [1, 2, 3],
show: function() {
this.players.forEach(function(entry) {
console.log(entry);
// this refers to the scope of the anonymous function, which is window
console.log(this);
});
}
}
//sport.show();
var sport2 = {
players: [3, 4, 5],
show: function() {
// this refers to the object scope in which it resides -
// in which case, that would be "sport2"
var self = this;
this.players.forEach(function(entry) {
console.log(entry);
// self is now synonymous with "this" in the sport2 scope.
console.log(self);
});
}
}
sport2.show();
编辑: self 可以在 show
函数本身内部设置,无需以丑陋的方式传递它。感谢评论部分指出了这一点。
关于javascript - 为什么会有这样的背景呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43621410/