JS绑定函数和函数调用操作符的性质 [英] Nature of JS bound functions and function invocation operator

查看:284
本文介绍了JS绑定函数和函数调用操作符的性质的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var obj = {};

var r1 = (obj['toString'])();
var m1 = obj['toString'];
var r2 = m1();

var r3 = (obj.toString)();
var m2 = obj.toString;
var r4 = m2();

r1 r3 预期包含正确的结果:[object Object],而 r2 r4 包含[object Undefined]显示 m1 m2 未绑定到对象。

r1 and r3 expectedly contain correct result: "[object Object]", while r2 and r4 contain "[object Undefined]" showing that m1 and m2 are not bound to object.

我无法完全理解 obj如何[ 'toString']()被执行。我总是这样看,(obj ['toString'])() - > (function obj)() 。事实证明,函数调用操作符回顾什么是上下文。我希望运营商不知道操作数的来源。

I can't fully comprehend how obj['toString']() is executed. I always looked this way, (obj['toString'])() -> (function obj)(). Turns out that function invocation operator looks back on what is the context. I would expect operator to not know where operands come from.

任何人都能正确解释这种行为吗?

Can anyone properly explain this behavior?

推荐答案


结果是函数调用操作符回顾上下文是什么。我希望操作员不知道操作数的来源。

Turns out that function invocation operator looks back on what is the context. I would expect operator to not know where operands come from.

事实上,它确实知道。

在EcmaScript规范中,这由属性访问者运营商描述(和一些类似的操作)返回一个参考对象,其中包含这些信息:访问该属性的上下文。任何正常操作通常只会获得参考值 - 包括赋值运算符,在您的情况下解散参考。

In the EcmaScript specification this is described by the property accessor operators (and a few similar operations) to return a "Reference object" that holds exactly this information: the context on which the property was accessed. Any "normal" operations will usually just get the reference's value - including the assignment operators, which do dissolve the reference in your case.

电话运算符使用此方法调用特殊方法:

The call operator uses this to make method calls special:



  1. ref 是评估 MemberExpression 的结果。 可能会返回参考

  2. func GetValue (ref)获取实际的函数对象 - 你在spec

  3. ... fetch参数中看到了很多这样的操作,做了一些类型的断言

  4. 如果Type( ref )是参考,那么

    • 如果IsPropertyReference( ref )为真,那么

      thisValue GetBase ref )。 < - 此处提取方法上下文

    • 否则, ref 的基础是环境记录

      ... 基本上描述中的变量语句

  1. Let ref be the result of evaluating MemberExpression. which may return a Reference
  2. Let func be GetValue(ref). which fetches the actual function object - you see this operation a lot in the spec
  3. fetch arguments, do some type assertions
  4. If Type(ref) is Reference, then
    • If IsPropertyReference(ref) is true, then
      Let thisValue be GetBase(ref). <- here the method context is fetched
    • Else, the base of ref is an Environment Record
      which basically describes variables inside a with statement


这篇关于JS绑定函数和函数调用操作符的性质的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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