为什么我得到不明确的价值

时间:2016-12-17 18:21:26

标签: 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 () function is defined in the global scope, just like the firstName and lastName
        alert (this.firstName + " " + this.lastName);
        }
        showFullName ();

3 个答案:

答案 0 :(得分:1)

如果正确执行,则此方法有效(将alert替换为console.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 Fiddle做了类似的事情



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




答案 1 :(得分:-1)

Normaly使用class ResourceDTO { // ... public void setResourceName(final String name) { this.resourceName = name; this.associateResource.forEach(a -> a.setAssociateName(name)); } } 关键字。 window独立于声明函数的位置,但取决于调用的位置(以及如何调用)。

this

答案 2 :(得分:-1)

所以我开始知道,当我们使用严格模式时,此关键字在全局函数中保存undefined的值。 但是,在严格模式下,它的值保持在进入执行上下文时设置的值,因此,在下面的例子中,这将默认为undefined:

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

    f2() === undefined;

因此,在严格模式下,如果执行上下文没有定义它,它仍然是未定义的。我从MDN获取了这段代码片段。

所以在我的情况下,价值并没有出现在小提琴中。但这将是@vlaz指出的理由。谢谢@vlaz