2017-03-02 18 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 
})(); 
相關問題