为什么在访问匿名自执行函数的参数时需要使用"this"关键字?

Why do I need to use the "this" keyword when accessing a parameter for an anonymous self-executing function?

我刚刚开始学习 Javascript,我一直在研究匿名自执行函数。我编写了一些无法按我预期的方式工作的代码。为什么在这种情况下需要 "this" 关键字来获取变量 "shoutIt" 的值?

第一个警报显示 "Did it work? (1) undefined",第二个警报显示 "Did it work? (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
})();

因为您的匿名函数需要 shoutIt 作为参数,但您没有向它传递任何内容。

基本上你的函数需要一个参数shoutIt。此参数将在函数的本地范围内。如果没有传递任何内容,当编译器获取 shoutIt 的值时,它现在将从本地范围访问它,而不会进入全局级别。在本地级别,因为您没有向函数传递任何内容,所以它会给您 undefined

有两种解决方法

1) 传递shoutIt的值

var shoutIt = "[YES!]";

//creating an anonymous, self-executing function
(
    function (shoutIt) { //expecting that value
        shoutItDebug = shoutIt;
        shoutItDebug = this.shoutIt;
        alert("Did it work? (1) " + shoutIt);
        alert("Did it work? (2) " + this.shoutIt)
})(shoutIt);**strong text** //passing argument to the function

2) 不传递任何参数

var shoutIt = "[YES!]";

//creating an anonymous, self-executing function
(
    function () {
        shoutItDebug = shoutIt;
        shoutItDebug = this.shoutIt;
        alert("Did it work? (1) " + shoutIt); 
        alert("Did it work? (2) " + this.shoutIt) 
})();

'this' 的工作原理

基本上'this'指的是javascript中的上下文。 默认情况下它指向 window 对象。尝试做

console.log(this) //outputs the window object

在全局级别定义的任何内容都会自动链接到 window 对象。

这里有两个叫shoutIt的变量:一个是var shoutIt定义的全局变量,一个是function (shoutIt) { ...[=24中形式参数定义的变量=]

当您在非严格模式下 运行 一个非方法函数(即形式为 foo() 而不是 bar.foo())时,this 等于全局对象(在浏览器中,window)。在函数内部,this.shoutIt 引用全局范围内的 shoutIt 变量。

相比之下,shoutIt 在这里指的是具有该名称的函数参数,而不是全局变量,后者是上一级作用域。 (全局变量是更直接的同名变量 "shadowed"。)该函数不使用任何参数调用,因此函数中 shoutIt 的值是 undefined

如果要传递一个值用作名为 shoutIt 的参数,请在调用括号中提供一个值:

(function (shoutIt) {
    ...
})(someValue);

您的参数与函数外部的变量同名,并且您没有将变量传递给函数。

对于您的示例,您可以做一些不同的事情来让它按预期工作。

一个。将 shoutIt 传递给函数

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
})(shoutIt);

乙。更改函数定义中的参数名称。

var shoutIt = "[YES!]";

//creating an anonymous, self-executing function
(
    function (shoutItAgain) {
        shoutItDebug = shoutIt;
        shoutItDebug = this.shoutIt;
        alert("Did it work? (1) " + shoutIt); //doesn't work, undefined
        alert("Did it work? (2) " + this.shoutIt) //works
})();