【发布时间】:2017-03-02 19:34:48
【问题描述】:
我刚刚开始学习 Javascript,并且一直在玩匿名自执行函数。我编写了一些无法按预期方式工作的代码。为什么在这种情况下需要“this”关键字来获取变量“shoutIt”的值?
第一个警报显示“它有效吗?(1) 未定义”,而第二个警报显示“它有效吗?(2) [YES!]”。
谢谢!
var shoutIt = "[YES!]";
//creating an anonymous, self-executing function
(
function (shoutIt) {
shoutItDebug = shoutIt;
shoutItDebug = this.shoutIt;
alert("Did it work? (1) " + shoutIt); //doesn't work, undefined
alert("Did it work? (2) " + this.shoutIt) //works
})();
【问题讨论】:
-
在您的代码中,
this不是函数,this是全局范围。将console.log(this)放入您的函数并检查输出。 -
你应该使用严格模式,然后它不会按预期工作。
-
我不知道有不同的模式。我会打开严格的,谢谢。
标签: javascript anonymous-function