为什么在表达式中忽略括号(o.method)() [英] Why parenthesis are ignored in the expression (o.method)()

查看:73
本文介绍了为什么在表达式中忽略括号(o.method)()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想理解为什么表达式

(o.method)()

被忽略,因此它的行为与<$相同c $ c> o.method(),执行上下文方法引用 o 。我期待它的行为类似于(o.method || true)(),其中执行上下文方法引用全局对象。

are ignored and so it's behaving equally to o.method(), with execution context of method referencing o. I was expecting it to behave similarly to (o.method || true)(), where execution context inside method references global object.

如果我自己评估(o.method),它会返回对独立引用的引用函数没有绑定到任何上下文。只需像这样重写它

If I evaluate (o.method) on its own, it returns reference to a standalone function not bound to any context. Simply rewriting it like this

var a = (o.method); a(); 

将具有预期的全局上下文。我只是通过替换 a 来缩短代码,并产生不同的结果。

will have global context as expected. And I've just shortened the code by replacing a, and it produced different result.

推荐答案

我认为它与 ES5 11.1.6 有关:


11.1.6分组运算符#Ⓣ

11.1.6 The Grouping Operator # Ⓣ

生产 PrimaryExpression :( Expression)评估如下:


  1. 返回评估结果表达式。这可能是参考类型。

  1. Return the result of evaluating Expression. This may be of type Reference.

注意此算法不会将GetValue应用于评估Expression的结果。这样做的主要动机是, delete typeof 等运算符可以应用于带括号的表达式。

NOTE This algorithm does not apply GetValue to the result of evaluating Expression. The principal motivation for this is so that operators such as delete and typeof may be applied to parenthesised expressions.

让我们看看如何在JS中完成函数调用:

Let's see how function invocation is done in JS:

关键点是 o.method 是一个参考(由规范定义):

The key point is that o.method is a Reference (as defined by the spec):


A引用是已解析的名称绑定。 Reference由三个组件组成,基值,引用名称和布尔值严格引用标志。

A Reference is a resolved name binding. A Reference consists of three components, the base value, the referenced name and the Boolean valued strict reference flag.

所以, o.method 不是函数YET;它基本上是 [[o,method,false]] 。当使用参数列表 o.method()调用时,GetValue将获取引用值,然后方法调用继续进行(如 11.2.3

So, o.method is not a Function YET; it is basically [[o, "method", false]]. When invoked with an argument list, o.method(), the reference value is taken by GetValue, then the method invocation proceeds (as described in 11.2.3).

当你做(o.method)()(o.method) 参考 - GetValue仍然没有适用它(根据引用的11.1.6)。所以没有任何改变。

When you do (o.method)(), (o.method) is still a Reference - GetValue has still not been applied to it (per the quoted 11.1.6). So nothing changes.

当你做(o.method || true)()时, || 将GetValue应用于左侧(根据 11.11 )并生成一个函数值 - 不再是Reference。因此,它不能被评估为方法调用,因为有关基础和引用名称(参考中存在)的信息将丢失。

When you do (o.method || true)(), || will apply GetValue to the left side (per 11.11) and produce a function value - not a Reference any more. Thus, it cannot be evaluated as a method invocation, since the information about the base and referenced name (that was present in Reference) is lost.

这篇关于为什么在表达式中忽略括号(o.method)()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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