2016-12-17 17 views
-1

我有這段代碼,當我運行它顯示未定義。但是,我們可以使用此關鍵字訪問全球資產。爲什麼我得到undefined值

var firstName = "Peter", 
     lastName = "Ally"; 

     function showFullName() { 
     // "this" inside this function will have the value of the window object 
     // because the showFullName() function is defined in the global scope, just like the firstName and lastName 
     alert (this.firstName + " " + this.lastName); 
     } 
     showFullName(); 
+1

http://jsbin.com/gerexi/1/edit?js,輸出 - 我無法重現該問題。 – Quentin

+0

我既不好也不好 –

+1

在嚴格模式下,它只是拋出一個錯誤。如果這是放置另一個函數,那麼它會顯示「undefined undefined」。 – vlaz

回答

-1

通常使用window關鍵字代替。 this是獨立的地方是功能宣佈,但依賴於(以及如何)被稱爲的地方。

var firstName = "Peter", 
    lastName = "Ally"; 

function showFullName() { 
    alert (window.firstName + " " + window.lastName); 
} 
showFullName(); 
-1

所以我才知道,當我們使用嚴格模式時,這個關鍵字在全局函數中保存了未定義的值。 在嚴格模式,但是,這個值保持在任何它被設置在進入執行上下文的時候,所以,在以下情況下,這將默認爲未定義:

function f2(){ 
     "use strict"; // see strict mode 
     return this; 
    } 

    f2() === undefined; 

所以,在嚴格模式下,如果這不是由執行上下文定義的,它仍然是未定義的。我已經從MDN獲取了這個代碼片段。

因此,在我的情況下,值不會出現在小提琴中。但它會是由@vlaz指出的原因。由於@vlaz

+0

如果您啓用嚴格模式比上面的代碼會引發錯誤。 – vlaz

1

這工作如果正確執行(更換alertconsole.log更容易的例子)

var firstName = "Peter", 
 
    lastName = "Ally"; 
 

 
function showFullName() { 
 
    // "this" inside this function will have the value of the window object 
 
    console.log("this and window are the same thing", this === window); 
 
    
 
    // because the showFullName() function is defined in the global scope, just like the firstName and lastName 
 
    console.log(this.firstName + " " + this.lastName); 
 
} 
 

 
showFullName();

如果這是放置在功能範圍它不會工作,但是 - 大概JS小提琴做那樣的事

(function() { 
 
    var firstName = "Peter", 
 
     lastName = "Ally"; 
 

 
    function showFullName() { 
 
     // "this" inside this function will still have the value of the window object 
 
     console.log("this and window are the same thing", this === window); 
 
     
 
     // however firstName and lastName are not goint to be attached to it because they are in functional scope 
 
     console.log("the names are still reachable", firstName, lastName) 
 
     
 
     //but not attached to the window object (which "this" points to) 
 
     console.log(this.firstName + " " + this.lastName); 
 
    } 
 

 
    showFullName(); 
 
})();

請注意,使用,如果你有strict mode enabled然後thisundefined,而不是window和代碼會產生一個錯誤

var firstName = "Peter", 
 
    lastName = "Ally"; 
 

 
function showFullName() { 
 
    "use strict"; 
 
    // "this" inside this function will now have the value "undefined" 
 
    console.log("'this' is actually 'undefined'", this); 
 
    console.log("the actual value 'undefined', not a string", typeof this); 
 
    
 
    // the following line will throw a TypeError because it's trying to get a property from "undefined" 
 
    console.log(this.firstName + " " + this.lastName); 
 
} 
 

 
showFullName();

相關問題