gpt4 book ai didi

javascript - javascript中括号与 `this`绑定(bind)的效果

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:39:09 26 4
gpt4 key购买 nike

我遇到一个非常棘手的案例:

class C {
// class method are implicit in strict mode by default
static method() { return this === undefined; }
}

C.method(); // => false
(0,C.method)(); // => true

为什么 (0, C.method) 在上面的例子中改变了 this 的绑定(bind)?

最佳答案

那是因为C.method 返回了一个引用

{ base: C, referencedName: "method", strict: strictFlag }

当你call it , JS获取函数使用GetValue使用该引用,并提供引用的基数 (C) 作为 this 值。

<i>CallExpression</i> : <i>MemberExpression</i> <i>Arguments</i>

1. Let <i>ref</i> be the result of evaluating <i>MemberExpression</i>. // <-- The reference
2. Let <i>func</i> be ? <a href="http://www.ecma-international.org/ecma-262/7.0/#sec-getvalue" rel="noreferrer noopener nofollow">GetValue</a>(<i>ref</i>). // <-- The function
4. If <a href="http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-data-types-and-values" rel="noreferrer noopener nofollow">Type</a>(<i>ref</i>) is <a href="http://www.ecma-international.org/ecma-262/7.0/#sec-reference-specification-type" rel="noreferrer noopener nofollow">Reference</a>, then
a. If IsPropertyReference(<i>ref</i>) is <b>true</b>, then
i. Let <i>thisValue</i> be <a href="http://www.ecma-international.org/ecma-262/7.0/#sec-getthisvalue" rel="noreferrer noopener nofollow">GetThisValue</a>(<i>ref</i>). // <-- C

但是,当您使用 comma operator ,您直接获得函数,而不是引用。

<i>Expression</i> : <i>Expression</i> <b>,</b> <i>AssignmentExpression</i>

1. Let <i>lref</i> be the result of evaluating <i>Expression</i>.
2. Perform ? <a href="http://www.ecma-international.org/ecma-262/7.0/#sec-getvalue" rel="noreferrer noopener nofollow">GetValue</a>(<i>lref</i>). // <-- 0
3. Let <i>rref</i> be the result of evaluating <i>AssignmentExpression</i>.
4. Return ? <a href="http://www.ecma-international.org/ecma-262/7.0/#sec-getvalue" rel="noreferrer noopener nofollow">GetValue</a>(<i>rref</i>). // <-- The function

由于没有引用,JS 无法知道基对象,所以调用时提供undefined作为this值。

<i>CallExpression</i> : <i>MemberExpression</i> <i>Arguments</i>

1. Let <i>ref</i> be the result of evaluating <i>MemberExpression</i>. // <-- The function
2. Let <i>func</i> be ? <a href="http://www.ecma-international.org/ecma-262/7.0/#sec-getvalue" rel="noreferrer noopener nofollow">GetValue</a>(<i>ref</i>). // <-- The function
5. Else <a href="http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-data-types-and-values" rel="noreferrer noopener nofollow">Type</a>(<i>ref</i>) is not <a href="http://www.ecma-international.org/ecma-262/7.0/#sec-reference-specification-type" rel="noreferrer noopener nofollow">Reference</a>,
1. Let <i>thisValue</i> be <b>undefined</b>. // <-- undefined

关于javascript - javascript中括号与 `this`绑定(bind)的效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52022176/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com