简体   繁体   English

为什么concat函数返回一个带有窗口的数组?

[英]Why does the concat function return an array with window in it?

I'm trying to wrap my head around this javascript snippet: 我正在尝试把这个javascript代码段包裹起来:

(_=[].concat)()[0]

It returns window, but why? 它返回窗口,但是为什么呢?

After breaking it down into its components it's easier to understand what's going on. 将其分解成各个组件后,更容易了解发生了什么。

You can basically rewrite this snippet as: 您基本上可以将此代码段重写为:

Array.prototype.concat.call(this)[0]

When you call a function, it gets its this context from the object before the . 调用函数时,它从之前的对象获取this上下文. , so the function call object.toString() will have its this reference set to object . ,因此函数调用object.toString()会将其this引用设置为object However, when a function doesn't have a containing object, its context will default to the global scope, meaning window in browsers. 但是,当一个函数没有包含对象时,其上下文将默认为全局范围,即浏览器中的window concat will normally use the existing array context it is called on to use as the base array to concatenate on to, but in this case window is the context, so it is cast into an array and then concat is applied to it, but since nothing is provided to be concatenated, it just returns an array with the context, which is window. concat通常将使用现有的数组上下文,将其用作连接的基础数组,但是在这种情况下, window是上下文,因此将其转换为数组,然后将concat应用于该数组,但是由于没有提供要串联的对象,它只返回带有上下文的数组,即window。

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

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