2017-03-02 45 views
0

我刚刚开始学习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 
})(); 
+0

在你的代码中,'this'不是函数,'this'是全局作用域。把'console.log(this)'放到你的函数中并检查输出。 – castis

+0

你应该使用严格模式,那么它不会按预期工作。 – Bergi

+0

我不知道有不同的模式。我会打开严格的,谢谢。 –

回答

1

因为您的匿名函数期望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 

OR

的价值

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

'这''如何工作

基本上'这'是指在JavaScript中的上下文。 默认情况下,它指向窗口对象。尝试做

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

无论在全局级定义什么,都会自动链接到窗口对象。

+1

谢谢,现在我只是没有按照我的意思去传递参数。不知道如何选择这个作为我的答案,但它帮了我很多! :) –

+0

很高兴能帮到@AustinGerschler –

2

有两个变量称为shoutIt这里:一个是var shoutIt定义的全局变量,另一种是当你运行一个非法功能function (shoutIt) { ...

由正式参数定义(即,一个变量表格foo()而不是bar.foo())在非严格模式下,this等于全局对象(在浏览器中,window)。在函数内部,this.shoutIt指全局范围内的shoutIt变量。

相比之下,shoutIt在这里指的是具有该名称的函数参数,而不是全局变量,它是一个范围级别。 (全局变量被相同名称的更直接变量“遮蔽”。)该函数不被任何参数调用,因此该函数内的shoutIt的值为undefined

如果你想在一个值传递作为调用括号命名为shoutIt的说法,供应一个使用方法:

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

你参数命名一样的变量的函数之外,你没有将一个变量传递给函数。

用你的例子,你可以做一些不同的事情来让它按照你的预期工作。

A.通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); 

B.改变你的函数定义的参数的名称。

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 
})(); 
相关问题