是否可以通过任何方式做这样的事情:
function A() {
var Loaded = 'loaded';
raise Loaded;
}
function A_raise(evt) {
console.log(evt);
}
A.prototype.constructor = A;
A.prototype.raise = A_raise;
关键部分是行:
raise Loaded;
最佳答案
在 JavaScript 中获得无括号函数调用的唯一方法是定义 setter/getter 属性,或重写特殊方法之一:toString
或 valueOf
。在这两种情况下,您都无法很好地控制传递给调用的参数。
function C() {}
C.prototype.valueOf = function () { alert("valueOf called"); };
var c = new C();
// No parentheses
+c;
您可以调用不带括号的构造函数,但同样不能传递参数。
function f() { alert("f"); }
// No parentheses
new f
<小时/>
不能插入的原因之一是分号插入。
f()
是一个函数调用,原样
f
()
和
if
(x) { }
是一个有效的条件,因为 if
是该语言的核心部分,但如果您可以从函数调用中删除括号,那么分号插入就必须将代码视为
var x = raise
y
作为初始化为调用函数结果的变量。
<小时/>既然您询问了语言扩展,EcmaScript 规范第 16 章表示允许解释器添加到语言的语法中,
An implementation may extend program syntax and regular expression pattern or flag syntax. To permit this, all operations (such as calling eval, using a regular expression literal, or using the Function or RegExp constructor) that are allowed to throw SyntaxError are permitted to exhibit implementation-defined behaviour instead of throwing SyntaxError when they encounter an implementation-defined extension to the program syntax or regular expression pattern or flag syntax.
所以自从
raise foo
不是语言中的有效表达式或陈述,他们可以允许,但他们不能以改变含义的方式这样做
raise
foo
其含义必须与
相同 raise;
foo
因此解释器必须raise
一个新的restricted production由于措辞,这是有问题的:
The following are the only restricted productions in the grammar:
这可能意味着不规范,但事实并非如此。
关于带有缺少括号的函数调用的 JavaScript 语言扩展 - 它们可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15118994/