[英]Scope of an object literal within a function inside the object
我正在運行三個代碼段。 第一個起作用,而第二個和第三個不起作用。 我不確定我是否理解第二個和第三個無效的原因。
user2 = {
handle :"mytext",
alertName: function(){
alert(this.handle);}
};
user2.handle; //"mytext"
user2.alertName() // alerts "mytext"
在這里,我了解到句柄已分配給user2對象,並且是user2對象上的鍵。 因此,當我調用user2.alertName()時,this.handle引用了user2.handle,因此輸出了正確的值。
但是,為什么以下兩個版本的代碼不起作用:
user2 = {
handle :"mytext",
alertName: function(){
alert(handle);}
};
user2.handle; //"mytext"
user2.alertName() // gives error that handle is not defined in the console
和
user2 = {
handle :"mytext",
alertName: function(handle){
alert(handle);}
};
user2.handle; //"mytext"
user2.alertName() //gives undefined in the alert popup
據我了解范圍,在user2對象定義的句柄應該可以用作user2的子作用域。 我是否在這里錯過了一些基本的東西。抱歉,這似乎是一個菜鳥問題,但我想我明白了,並一直回到這里。 而且,我在尋找文檔時為何對第二個或第三個沒有意義的地方一無所知。
在第二和第三代碼中:
user2 = {
handle :"mytext", // handle is a property
alertName: function(){
alert(handle);}
};
由於句柄不是變量定義的,因此會出現錯誤。 在第三種情況下,您將句柄定義為方法簽名中的參數,但未在調用中傳遞任何參數,因此它以未定義形式出現。
user2 = {
handle :"mytext",
alertName: function(){
alert(handle);}
};
user2.handle; //"mytext"
user2.alertName() // gives error that handle is not defined in the console
handle
是property
的的object
,所以你需要通過訪問該對象的屬性this
是指的object
。
alert(handle);
拋出錯誤,原因是它試圖找到一個不在范圍內的名為handle的變量。
如果globally
定義了變量句柄,則可以在user2
object
訪問它。
var handle="google";
user2 = {
handle :"mytext",
alertName: function(){
alert(handle);}
};
alert(user2.handle); //"mytext"
user2.alertName() // gives error that handle is not defined in the console
在第二個示例中,函數“ alertName”需要參數“ handle”。 調用不帶參數結果的user2.alertName()導致未定義。
對於作品應該是這樣的:
user2.alertName(user2.handle);
我將從代碼示例開始,然后進行解釋。
var user2 = {
handle :"mytext",
alertName: function() {
//var handle is not defined in the current lexical scope or globally.
alert(handle);
}
};
user2.handle; //"mytext"
user2.alertName() // gives error that handle is not defined in the console
說明:您正在定義user2.alertName
。 在此函數中,您正在調用alert(handle)
。 從我可以看到, handle
未在當前詞法范圍內定義,也未全局undefined
,因此undefined
會發出警報。
var user2 = {
handle :"mytext",
alertName: function(handle){
alert(handle);
}
};
user2.handle; //"mytext"
user2.alertName() //gives undefined in the alert popup
說明:您正在定義user2.alertName
。 該功能采用一個被警告的參數。 當您調用user2.alertName()
您沒有傳遞任何變量或文字。 因此, undefined
的警報。 提醒user2.handle
使用:
user2.alertName(user2.handle);
我希望這有幫助,
里斯
user2 = {
handle :"mytext",
alertName: function(){
alert(this.handle);}
};
user2.handle; //"mytext"
user2.alertName() // alerts "mytext"
handle是對象的屬性,因此您需要通過引用對象的對象來訪問該對象的屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.