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()

後續補充

...

 

 

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