简体   繁体   中英

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

I'm trying to wrap my head around this javascript snippet:

(_=[].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 . , so the function call object.toString() will have its this reference set to object . However, when a function doesn't have a containing object, its context will default to the global scope, meaning window in browsers. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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