Javascript 为什么我得到未定义的值

Javascript 为什么我得到未定义的值,javascript,scope,this,global,Javascript,Scope,This,Global,我有这个代码,当我运行它显示未定义。但是,我们可以使用此关键字访问全局属性 var firstName = "Peter", lastName = "Ally"; function showFullName () { // "this" inside this function will have the value of the window object // because the showFullName () func

我有这个代码,当我运行它显示未定义。但是,我们可以使用此关键字访问全局属性

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

通常使用
窗口
关键字代替
独立于函数声明的位置,但取决于调用的位置(以及方式)


所以我知道,当我们使用strict模式时,这个关键字在全局函数中包含undefined的值。 但是,在严格模式下,该值保持在输入执行上下文时设置的值,因此,在以下情况下,该值将默认为未定义:

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

    f2() === undefined;
因此,在严格模式下,如果这不是由执行上下文定义的,它仍然是未定义的


所以在我的例子中,价值并没有出现在小提琴上,但这将是@vlaz指出的原因。感谢@vlaz

如果执行正确,此功能将正常工作(将
警报
替换为
控制台.log
以获得更简单的示例)

var firstName=“Peter”,
lastName=“Ally”;
函数showFullName(){
//此函数中的“this”将具有窗口对象的值
log(“这和窗口是同一件事”,this==窗口);
//因为showFullName()函数是在全局范围内定义的,就像firstName和lastName一样
console.log(this.firstName+“”+this.lastName);
}

showFullName()-我不能重现这个问题。我也不知道它是okIn strict模式,它应该抛出一个错误。如果将其放在另一个函数中,那么它将显示“undefined undefined”。请签入fiddle。@在这种情况下,user1989488 fiddle显然没有在全局范围内运行代码。如果启用了严格模式,则上述代码将抛出错误。
 function f2(){
      "use strict"; // see strict mode
      return this;
    }

    f2() === undefined;