有人可以解释这个Javascript方法吗? [英] Can somebody explain this Javascript method?

查看:179
本文介绍了有人可以解释这个Javascript方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

原始来源: http://twitter.com/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:


  1. window 被允许为宿主对象而不是本地对象;在这种情况下,关于你可以传递给其他原型方法的保证并不一定适用;和

  2. 如果窗口实际上有帧/ iframe,它会尝试反转它们的顺序,这不起作用,因为帧集是只读的。

  1. window is allowed to be a "host object" rather than a "native object"; in this case the guarantees about what you can pass to other prototypes' methods don't necessarily apply; and
  2. if the window actually has frames/iframes, it would try to reverse their order, which wouldn't work because the frame collection is read-only.

然而,在当前的浏览器中,前一种情况确实有效,而后一种情况无声地失败而没有错误,所以你仍然得到 ===窗口行为而不是例外。

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方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆