2016-12-17 67 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();

相关问题