我是 js 新手。我真的不明白它是如何this
工作的。我有几个例子,它们在 codesandbox.io、create-react-app、使用 strict 和不使用 strict 中的工作方式不同。
示例 1
var obj = {
id: "awesome",
cool: function coolFn() {
console.log( this);
}
};
var id = "not awesome";
obj.cool();
setTimeout( obj.cool, 100 );
在代码沙箱中Object {id: "awesome", cool: function coolFn()}, null
。
在使用严格 {id: "awesome", cool: ƒ},Window{...}
。
在不使用严格{id: "awesome", cool: ƒ},Window{...}
的 .
在 create-react-app {id: "awesome", cool: ƒ},Window{...}
中。
示例 2
var obj = {
id: "awesome",
cool: () => {
console.log(this);
}
};
var id = "not awesome";
obj.cool();
setTimeout(obj.cool, 100);
在代码沙箱中undefined, undefined
。
在使用严格 Window{...},Window{...}
。
在不使用严格Window{...},Window{...}
的 .
在 create-react-app undefined , undefined
中。
谁能解释我的例子中发生了什么?