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

1.应用场景

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

2.学习/操作

暂时参考:

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

http://www.ruanyifeng.com/blog/2018/06/javascript-this.html  //JavaScript 的 this 原理  - 阮一峰的网络日志

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

https://wangdoc.com/javascript/oop/this.html  //阮一峰 - this 关键字

1.出现this的原因:

JavaScript 语言之所以有this的设计,跟内存里面的数据结构有关系。

整理后发出

...

备用代码://需要弄懂

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;

截图:

后续补充

...

3.问题/补充

TBD

4.参考

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

http://www.ruanyifeng.com/blog/2018/06/javascript-this.html  //JavaScript 的 this 原理  - 阮一峰的网络日志

https://wangdoc.com/javascript/oop/this.html  //阮一峰 - this 关键字

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

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

后续补充

...

猜你喜欢

转载自blog.csdn.net/william_n/article/details/105845636