【问题标题】:Why such a context? [duplicate]为什么会有这样的背景? [复制]
【发布时间】:2017-04-25 21:38:07
【问题描述】:

为什么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 的范围取决于执行上下文并且是后期绑定的。搜索 SO 和网络,您会发现很多关于此的讨论。
  • "如果给forEach()提供了thisArg参数,则作为回调的this值。否则,将undefined的值作为它的this值。回调最终可观察到的this值是根据确定函数看到的 this 的通常规则确定。” - developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
  • "use strict";
  • 为什么是sport 对象而不是sport.players 数组?

标签: javascript


【解决方案1】:

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

【讨论】:

  • 为什么投反对票?
  • 因为this 几乎从不引用一个函数
  • 建议:函数内可以定义var self = this;
  • @Nayuki 这也行不通,因为该方法何时被称为其上下文它的 windows 对象
  • 如果答案可以接受,请查看并删除反对票。我不想误导未来的 SO'ers。
猜你喜欢
  • 2019-05-20
  • 2021-09-21
  • 2015-12-23
  • 1970-01-01
  • 1970-01-01
  • 2020-01-19
  • 2021-02-20
  • 1970-01-01
相关资源
最近更新 更多