gpt4 book ai didi

javascript - 为什么 funcname() = value;有效的语法?

转载 作者:行者123 更新时间:2023-12-03 02:30:16 26 4
gpt4 key购买 nike

another question ,有人有一个不正确的类定义,其中包含如下代码:

var myClass = function() {
...
this.name() = function() { ... };
}

明显的错误是该方法应该用 this.name = ... 来定义,而 name 后面没有括号。当您调用构造函数时,您会收到错误,因为 this.name 未定义。我在控制台中创建了一个更简单的示例:

foo() = 3;      // Causes: ReferenceError: foo is not defined
function foo() {};
foo() = 3; // Causes: ReferenceError: Invalid left-hand side in assignment

是否存在函数可以返回可分配的内容的上下文?我认为 Javascript 没有像 C++ 或 PHP 那样可以分配的引用。为什么这不会导致语法错误,而是根据函数是否定义而产生不同的错误?

最佳答案

引自ECMA Script 5.1 Specification for References ,

For example, the left-hand operand of an assignment is expected to produce a reference. The behaviour of assignment could, instead, be explained entirely in terms of a case analysis on the syntactic form of the left-hand operand of an assignment operator, but for one difficulty: function calls are permitted to return references. This possibility is admitted purely for the sake of host objects. No built-in ECMAScript function defined by this specification returns a reference and there is no provision for a user-defined function to return a reference. (Another reason not to use a syntactic case analysis is that it would be lengthy and awkward, affecting many parts of the specification.)

<小时/>

Is there any context where a function could return something that can be assigned to?

所以,不。没有用户定义的函数可以返回我们可以为其赋值的引用。

Why doesn't this cause a syntax error, rather than different errors depending on whether the function is defined or not?

正如规范中提到的,语法分析将是冗长、笨拙的,并且会影响规范的许多部分。因此,语法检查尚未完成。

关于javascript - 为什么 funcname() = value;有效的语法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26550996/

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