为何如此背景?

时间:2017-04-25 21:38:07

标签: javascript

为什么7行返回对象窗口

为什么不是运动对象?

var sport = {
caption: "2017",
players :  [{"name":"cat"},{"name":"dog"}] ,
show: function() {
  this.players.forEach(function(entry) {
      console.log(entry.name);
      console.log(this);//window
  });
}
}

sport.show();

https://jsfiddle.net/6qkj2byk/

1 个答案:

答案 0 :(得分:1)

this指的是它所在的匿名函数的范围,即窗口。

var sport = {
  players: [1, 2, 3],
  show: function() {
    this.players.forEach(function(entry) {
      console.log(entry);
      
      // this refers to the scope of the anonymous function, which is window
      console.log(this);
    });
  }
}

//sport.show();


var sport2 = {
  players: [3, 4, 5],
  show: function() {

    // this refers to the object scope in which it resides - 
    // in which case, that would be "sport2"
    var self = this;
    this.players.forEach(function(entry) {
      console.log(entry);

      // self is now synonymous with "this" in the sport2 scope.
      console.log(self);
    });
  }
}

sport2.show();

编辑:self可以在show函数本身内部设置,不需要以丑陋的方式传递它。感谢评论部分指出这一点。