Javascript this到底是什么, 应该怎么用?

1.应用场景

学习前端知识, 弄清楚this,有助于我们进行前端项目开发, 提高效率以及少踩坑.

2.学习/操作

整理后发出

...

 

 

备用代码:

 

function Counter() {
  this.sum = 0;
  this.count = 0;
}
Counter.prototype.add = function(array) {
  console.log(this);
  array.forEach(function(entry) {
    this.sum += entry;
    console.log(this);
    ++this.count;
  }, this);
  // ^---- Note
};

const obj = new Counter();
obj.add([2, 5, 9]);
obj.count;
// 3 === (1 + 1 + 1)
obj.sum;

截图:

Javascript this到底是什么, 应该怎么用?

 

 

后续补充

...

3.问题/补充

TBD

4.参考

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/this   //this

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach  //Array.prototype.forEach()

https://time.geekbang.org/column/article/128427   //11 | this:从JavaScript执行上下文的视角讲清楚this

后续补充

...