简体   繁体   English

如果我使用function.apply(undefined,args),为什么将this设置为window?

[英]Why is `this` set to `window` if I use `function.apply(undefined, args)`?

Take a look at this example: 看一下这个例子:

function aaa () {
    console.dir(this)
}

function bbb () {}

aaa.apply(undefined, [1,2,3]) // this in aaa is `window` object
aaa.apply(bbb, [1,2,3]) // this in aaa is `bbb` function

Why is this set to window in first apply case, even though I'm trying to force it to be undefined ? 为什么在第一个应用案例中this设置为window ,即使我试图将其设置为undefined

When not in strict mode and either null or undefined is passed as the first argument to .apply() , this will be set to the global object which is window in a browser. 当不严格模式,要么nullundefined作为对第一个参数传递.apply() this将被设置为全局对象是window中的浏览器。

In strict mode, it would set this to the actual value you pass. 在严格模式下,它会设置this给你传递的实际值。


In general non-strict mode tried to be tolerant of mistakes and even "fix" some mistakes automatically for you. 通常,非严格模式会尝试容忍错误,甚至会自动为您“修复”一些错误。 This proved to sometimes be a problem because things that should have been immediate coding errors were "covered up" by the system. 事实证明,这有时是个问题,因为系统本应“发现”本应为立即编码错误的内容。 strict mode was invented for a number of reasons and one of the reasons was to stop hiding coding errors. 发明严格模式的原因有很多,原因之一是停止隐藏编码错误。

Because that's how function calls work if you're not in strict mode . 因为如果您不在严格模式下 ,这就是函数调用的工作方式 Without strict mode, a function's this reference always refers to an object, and it'll be the global object (ie window ) if no other object was given. 没有严格模式,函数的this引用始终引用一个对象,如果没有其他对象,它将成为全局对象(即window )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM