考虑以下代码:
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)
按预期工作.
为什么有区别?
你的代码实际上是:
function Foo() {
}
Foo.prototype.alert = function() {
alert(this);
}(new Foo()).alert();
Run Code Online (Sandbox Code Playgroud)
由于缺少分号,请添加分号,它将正常运行.
您似乎缺少一个分号:
\n\nfunction Foo() {\n}\n\nFoo.prototype.alert = function() {\n alert(this);\n}; //Semi-colon here!\n\n(new Foo()).alert();\xe2\x80\x8b\nRun Code Online (Sandbox Code Playgroud)\n\n这是一个小提琴,它似乎可以按您的预期工作。
\n\n实际发生的情况是,该alert方法立即被调用,并Foo传入一个新实例,然后alert在返回值(即undefined)上调用:
Foo.prototype.alert = function() {\n alert(this);\n}(new Foo()).alert();\nRun Code Online (Sandbox Code Playgroud)\n\n正如@Nemoy 所提到的,如果您只是使用,new Foo().alert()您将获得预期的行为,因为自动分号插入会将分号放在正确的位置(缺少分号不会改变代码)。并且作为new运算符具有最高优先级,因此不需要括号。
| 归档时间: |
|
| 查看次数: |
109 次 |
| 最近记录: |