我刚刚开始学习Javascript,我一直在玩匿名的自我执行功能。我做了一些不能按我期望的方式工作的代码。为什么在这个例子中需要“this”关键字来获得变量“shoutIt”的值?为什么在访问匿名自执行函数的参数时需要使用“this”关键字?
第一个警告显示“有效吗?(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)'放到你的函数中并检查输出。 – castis
你应该使用严格模式,那么它不会按预期工作。 – Bergi
我不知道有不同的模式。我会打开严格的,谢谢。 –