为什么内联实例创建行为不同?

Itt*_*ayD 7 javascript

考虑以下代码:

function Foo() {
}

Foo.prototype.alert = function() {
    alert(this);
}

(new Foo()).alert();
Run Code Online (Sandbox Code Playgroud)

执行时(在jsfiddle中),警报显示'this'是窗口对象.将最后一行更改为:

var foo = new Foo();
foo.alert();
Run Code Online (Sandbox Code Playgroud)

按预期工作.

为什么有区别?

Esa*_*ija 6

你的代码实际上是:

function Foo() {
}

Foo.prototype.alert = function() {
    alert(this);
}(new Foo()).alert();
Run Code Online (Sandbox Code Playgroud)

由于缺少分号,请添加分号,它将正常运行.


Jam*_*ice 4

您似乎缺少一个分号:

\n\n
function Foo() {\n}\n\nFoo.prototype.alert = function() {\n    alert(this);\n}; //Semi-colon here!\n\n(new Foo()).alert();\xe2\x80\x8b\n
Run Code Online (Sandbox Code Playgroud)\n\n

这是一个小提琴,它似乎可以按您的预期工作。

\n\n

实际发生的情况是,该alert方法立即被调用,并Foo传入一个新实例,然后alert在返回值(即undefined)上调用:

\n\n
Foo.prototype.alert = function() {\n    alert(this);\n}(new Foo()).alert();\n
Run Code Online (Sandbox Code Playgroud)\n\n

正如@Nemoy 所提到的,如果您只是使用,new Foo().alert()您将获得预期的行为,因为自动分号插入会将分号放在正确的位置(缺少分号不会改变代码)。并且作为new运算符具有最高优先级,因此不需要括号。

\n