gpt4 book ai didi

javascript - 为什么会有这样的背景呢?

转载 作者:行者123 更新时间:2023-12-03 04:27:51 26 4
gpt4 key购买 nike

为什么第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();

https://jsfiddle.net/6qkj2byk/

最佳答案

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/

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