javascript - 为什么会有这样的背景呢?

标签 javascript

为什么第7行返回对象window

为什么不是运动对象?

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/

最佳答案

this 指的是它所在的匿名函数的作用域,即 window。

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 函数本身内部设置,无需以丑陋的方式传递它。感谢评论部分指出了这一点。

关于javascript - 为什么会有这样的背景呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43621410/

相关文章:

javascript - 工具提示内容未定义 - 谷歌地图

javascript - 带有 async/await 的递归 setTimeout

javascript - 使用 enzyme 进行 React/Redux 测试

javascript - 查看 HTML 高度是按样式还是按内容设置的

javascript - 将值传递给不同的网页表单

javascript - JavaScript 中关于样式指南的 'standard' 是什么?

javascript - 删除 :before or :after CSS element and it's property with Jquery

javascript - 请求 Javascript/Angular 遇到异步问题

javascript - 如何强制录制WebRTC音频的时间限制

javascript - javascript 中的 keycode 和 fromCharCode