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;

截圖:

 

 

後續補充

...

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

後續補充

...

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章