原始来源: twitter/tobeytailor/status/8998006366
(x=[].reverse)() === window // true我注意到这种行为会影响所有本机类型。究竟发生了什么?
I've noticed that this behavior affects all the native types. What exactly is happening here?
推荐答案这与奇怪的方式有关这个绑定适用于JavaScript。
This is to do with the weird way this binding works in JavaScript.
[].reverse是空列表中的方法 reverse 。如果您通过以下方式之一致电:
is the method reverse on an empty list. If you call it, through one of:
[].reverse(); []['reverse'](); ([].reverse)();然后执行此绑定到列表实例 [] 。但如果你分开它:
then it executes with this bound to the list instance []. But if you detach it:
x= [].reverse; x();它执行时没有这个 -binding,所以函数中的这个指向全局( window )对象,这是JavaScript中最糟糕,最误导性的设计错误之一。
it executes with no this-binding, so this in the function points to the global (window) object, in one of JavaScript's worst, most misleading design mistakes.
(x=[].reverse)()也在进行分离。赋值运算符返回它传递的相同函数对象,因此看起来它什么都不做,但它有副作用打破导致JavaScript绑定的有限特殊情况 this 。
Is also doing the detach. The assignment operator returns the same function object it was passed so it looks like it's doing nothing, but it has the side-effect of breaking the limited special case that causes JavaScript to bind this.
所以你说:
Array.prototype.reverse.call(window)反向,像许多其他 Array.prototype 方法一样,ECMAScript定义它可以处理任何类似本机序列的对象。它使用数字字符串键(最多 object.length )反转项目并返回该对象。所以它将返回传入的对象,该对象具有 length 属性。
reverse, like many other Array.prototype methods, is defined by ECMAScript to work on any native sequence-like object. It reverses the items with number-string keys (up to object.length) and returns the object. So it'll return the object that was passed in for any type that has a length property.
window 有一个length属性,对应于 window.frames.length ,所以用调用此方法这个指向窗口将起作用并返回窗口。理论上它可能仍然失败,因为:
window has a length property, which corresponds to window.frames.length, so calling this method with this pointing at window will work and return the window. In theory it may still fail, because:
然而,在当前的浏览器中,前一种情况确实有效,而后一种情况无声地失败而没有错误,所以你仍然得到 ===窗口行为而不是例外。
However, in current browsers the former case does work and the latter fails silently without an error, so you still get the ===window behaviour and not an Exception.
更多推荐
有人可以解释这个Javascript方法吗?
发布评论