成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

JavaScript中this的運行機制及爬坑指南

開發 前端
在 JavaScript 中,this 這個特殊的變量是相對比較復雜的,因為 this 不僅僅用在面向對象環境中,在其他任何地方也是可用的。 本篇博文中會解釋 this 是如何工作的以及使用中可能導致問題的地方,最后奉上最佳實踐。

[[222693]]

在 JavaScript 中,this 這個特殊的變量是相對比較復雜的,因為 this 不僅僅用在面向對象環境中,在其他任何地方也是可用的。 本篇博文中會解釋 this 是如何工作的以及使用中可能導致問題的地方,***奉上***實踐。

為了更好地理解 this,將 this 使用的場景分成三類:

  • 在函數內部 this 一個額外的,通常是隱含的參數。
  • 在函數外部(***作用域中): 這指的是瀏覽器中的全局對象或者 Node.js 中一個模塊的輸出。
  • 在傳遞給eval()的字符串中: eval() 或者獲取 this 當前值值,或者將其設置為全局對象,取決于 this 是直接調用還是間接調用。

我們來看看每個類別。

this 在函數中

這是最常用的 this 使用方式,函數通過扮演三種不同的角色來表示 JavaScript 中的所有可調用結構體:

  • 普通函數(this 在非嚴格模式下為全局對象,在嚴格模式下為undefined)
  • 構造函數(this 指向新創建的實例)
  • 方法(this 是指方法調用的接收者)

在函數中,this 通常被認為是一個額外的,隱含的參數。

this 在普通函數中

在普通函數中,this 的值取決于模式:

非嚴格模式: this 是指向全局對象 (在瀏覽器中為window對象)。

 

  1. function sloppyFunc() {  
  2.     console.log(this === window); // true  
  3.  
  4. sloppyFunc(); 

 

嚴格模式: this 的值為 undefined。

 

  1. function strictFunc() {  
  2.     'use strict' 
  3.     console.log(this === undefined); // true  
  4.  
  5. strictFunc(); 

 

也就是說,this 是一個設定了默認值(window或undefined)的隱式參數。 但是,可以通過 call() 或 apply() 進行函數調用,并明確指定this的值:

 

  1. function func(arg1, arg2) {  
  2.     console.log(this); // a  
  3.     console.log(arg1); // b  
  4.     console.log(arg2); // c  
  5.  
  6. func.call('a''b''c'); // (this, arg1, arg2)  
  7. func.apply('a', ['b''c']); // (this, arrayWithArgs) 

 

this 在構造函數中

如果通過new運算符調用函數,則函數將成為構造函數。 該運算符創建一個新的對象,并通過this傳遞給構造函數:

 

  1. var savedThis;  
  2. function Constr() { 
  3.     savedThis = this;  
  4.  
  5. var inst = new Constr();  
  6. console.log(savedThis === inst); // true  
  7. 在JavaScript中實現,new運算符大致如下所示(更精確的實現稍微復雜一點):  
  8. function newOperator(Constr, arrayWithArgs) {  
  9.     var thisValue = Object.create(Constr.prototype);  
  10.     Constr.apply(thisValue, arrayWithArgs);  
  11.     return thisValue;  

 

this 在方法中

在方法中,類似于傳統的面向對象的語言:this指向接受者,方法被調用的對象。

 

  1. var obj = {  
  2.     method: function () {  
  3.         console.log(this === obj); // true  
  4.     }  
  5.  
  6. obj.method(); 

 

this 在***作用域中

在瀏覽器中,頂層作用域是全局作用域,它指向 global object(如window):

 

  1. console.log(this === window); // true 

在Node.js中,通常在模塊中執行代碼。 因此,***作用域是一個特殊的模塊作用域:

 

  1. // `global` (不是 `window`) 指全局對象:  
  2. console.log(Math === global.Math); // true  
  3.  
  4. // `this` 不指向全局對象:  
  5. console.log(this !== global); // true  
  6. // `this` refers to a module’s exports:  
  7. console.log(this === module.exports); // true 

 

this 在 eval() 中

eval() 可以被直接(通過真正的函數調用)或間接(通過其他方式)調用。

如果間接調用evaleval() ,則this指向全局對象:

 

  1. (0,eval)('this === window' 
  2. true 

 

否則,如果直接調用eval() ,則this與eval()的環境中保持一致。 例如:

 

  1. // 普通函數  
  2. function sloppyFunc() {  
  3.     console.log(eval('this') === window); // true  
  4.  
  5. sloppyFunc();  
  6.  
  7. function strictFunc() {  
  8.     'use strict' 
  9.     console.log(eval('this') === undefined); // true  
  10.  
  11. strictFunc();  
  12.  
  13. // 構造器  
  14. var savedThis;  
  15. function Constr() {  
  16.     savedThis = eval('this');  
  17.  
  18. var inst = new Constr();  
  19. console.log(savedThis === inst); // true   
  20.  
  21. // 方法  
  22. var obj = {  
  23.     method: function () {  
  24.         console.log(eval('this') === obj); // true  
  25.     }  
  26.  
  27. obj.method(); 

 

與this相關的陷阱

有三個你需要知道的與this相關的陷阱。請注意,在各種情況下,嚴格模式更安全,因為this在普通函數中為undefined,并且會在出現問題時警告。

陷阱:忘記new操作符

如果你調用一個構造函數時忘記了new操作符,那么你意外地將this用在一個普通的函數。this會沒有正確的值。 在非嚴格模式下,this指向window對象,你將創建全局變量:

 

  1. function Point(x, y) {  
  2.     this.x = x;  
  3.     this.y = y;  
  4.  
  5. var p = Point(7, 5); // 忘記new!  
  6. console.log(p === undefined); // true   
  7.  
  8. // 創建了全局變量:  
  9. console.log(x); // 7  
  10. console.log(y); // 5  
  11. 幸運的是,在嚴格模式下會得到警告(this === undefined):  
  12. function Point(x, y) {  
  13.     'use strict' 
  14.     this.x = x;  
  15.     this.y = y;  
  16.  
  17. var p = Point(7, 5);  
  18. // TypeError: Cannot set property 'x' of undefined 

 

陷阱:不正確地提取方法

如果獲取方法的值(不是調用它),則可以將該方法轉換為函數。 調用該值將導致函數調用,而不是方法調用。 當將方法作為函數或方法調用的參數傳遞時,可能會發生這種提取。 實際例子包括setTimeout()和事件注冊處理程序。 我將使用函數callItt() 來模擬此用例:

 

  1. /**類似setTimeout() 和 setImmediate() */  
  2. function callIt(func) {  
  3.     func();  

 

如果在非嚴格模式下把一個方法作為函數來調用,那么this將指向全局對象并創建全局變量:

 

  1. var counter = { 
  2.     count: 0, 
  3.     // Sloppy-mode method 
  4.     inc: function () { 
  5.         this.count++; 
  6.     } 
  7. callIt(counter.inc); 
  8. // Didn’t work
  9. console.log(counter.count); // 0 
  10. // Instead, a global variable has been created 
  11. // (NaN is result of applying ++ to undefined): 
  12. console.log(count); // NaN 

 

如果在嚴格模式下把一個方法作為函數來調用,this為undefined。 同時會得到一個警告:

 

  1. var counter = {  
  2.     count: 0,  
  3.     // Strict-mode method  
  4.     inc: function () {  
  5.         'use strict' 
  6.         this.count++;  
  7.     }  
  8.  
  9.  
  10. callIt(counter.inc);  
  11. // TypeError: Cannot read property 'count' of undefined  
  12. console.log(counter.count);  
  13. 修正方法是使用bind():  
  14. var counter = {  
  15.     count: 0,  
  16.     inc: function () {  
  17.         this.count++;  
  18.     }  
  19.  
  20. callIt(counter.inc.bind(counter));  
  21.  
  22. // 成功了!  
  23. console.log(counter.count); // 1 

 

bind()創建了一個新的函數,它總是能得到一個指向counter的this。

陷阱:shadowing this

當在一個方法中使用普通函數時,很容易忘記前者具有其自己this(即使其不需要this)。 因此,你不能從前者引用該方法的this,因為該this會被遮蔽。 讓我們看看出現問題的例子:

 

  1. var obj = {  
  2.     name'Jane' 
  3.     friends: [ 'Tarzan''Cheeta' ],  
  4.     loop: function () {  
  5.         'use strict' 
  6.         this.friends.forEach(  
  7.             function (friend) {  
  8.                 console.log(this.name+' knows '+friend);  
  9.             }  
  10.         );  
  11.     }  
  12. };  
  13. obj.loop();  
  14. // TypeError: Cannot read property 'name' of undefined 

在前面的例子中,獲取this.name失敗,因為函數的this個是undefined,它與方法loop()的不同。 有三種方法可以修正this。

修正1: that = this。 將它分配給一個沒有被遮蔽的變量(另一個流行名稱是self)并使用該變量。

 

  1. loop: function () {  
  2.     'use strict' 
  3.     var that = this;  
  4.     this.friends.forEach(function (friend) {  
  5.         console.log(that.name+' knows '+friend);  
  6.     });  

 

修正2: bind()。 使用bind()來創建一個this總是指向正確值的函數(在下面的例子中該方法的this)。

 

  1. loop: function () {  
  2.     'use strict' 
  3.     this.friends.forEach(function (friend) {  
  4.         console.log(this.name+' knows '+friend);  
  5.     }.bind(this));  

 

修正3: forEach的第二個參數。 此方法具有第二個參數,this值將作為此值傳遞給回調函數。

 

  1. loop: function () {  
  2.     'use strict' 
  3.     this.friends.forEach(function (friend) {  
  4.         console.log(this.name+' knows '+friend);  
  5.     }, this);  

 

***實踐

從概念上講,我認為普通函數沒有它自己的this,并且想到上述修復是為了保持這種想法。 ECMAScript 6通過箭頭函數支持這種方法 - 沒有它們自己的this。 在這樣的函數里面,你可以自由使用this,因為不會被屏蔽:

 

  1. loop: function () {  
  2.     'use strict' 
  3.     // The parameter of forEach() is an arrow function  
  4.     this.friends.forEach(friend => {  
  5.         // `this` is loop’s `this`  
  6.         console.log(this.name+' knows '+friend);  
  7.     });  

 

我不喜歡使用this作為普通函數的附加參數的API:

 

  1. beforeEach(function () {  
  2.     this.addMatchers({  
  3.         toBeInRange: function (start, end) {  
  4.             ...  
  5.         }  
  6.     });  
  7. }); 

 

將這樣的隱含參數變成明確的參數使得事情更加明顯,并且與箭頭函數兼容。

 

  1. beforeEach(api => {  
  2.     api.addMatchers({  
  3.         toBeInRange(start, end) {  
  4.             ...  
  5.         }  
  6.     });  
  7. });  

 

責任編輯:龐桂玉 來源: 前端大全
相關推薦

2019-10-11 09:00:00

JavaScriptEvent Loop前端

2015-11-20 11:20:54

js開發

2022-02-11 23:11:09

Kubernetes集群容器化

2019-08-15 10:17:16

Webpack運行瀏覽器

2019-05-10 14:00:21

小程序運行機制前端

2009-12-11 10:52:37

PHP運行機制

2009-02-03 14:00:20

PHP運行PHP調用PHP原理

2015-11-16 11:17:30

PHP底層運行機制原理

2010-09-28 11:05:49

jQuery

2010-02-01 17:19:30

C++運行機制

2010-05-06 17:54:54

Oracle鎖

2018-12-26 16:30:09

SQL Server內部運行機制數據庫

2010-01-05 16:10:21

.NET Framew

2023-05-26 08:01:01

FacebookVelox機制

2010-02-23 10:15:22

WCF運行機制

2012-03-06 10:22:00

程序

2016-12-14 14:41:20

Hello World程序運行機制

2009-10-22 17:10:04

CLR和JRE運行機制

2016-12-13 14:12:25

程序機制

2013-05-08 12:42:39

HTTP協議IIS原理ASP.NET
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 久久精彩视频 | 婷婷毛片 | 91在线免费视频 | 久色 | 欧美一级大黄 | 国产亚洲一区二区三区在线 | 伊人网伊人网 | 精品久久久久久久久久久久久久 | 亚洲一区二区三区观看 | 久久综合伊人一区二区三 | 成人a网 | 日本a级大片| 国产日产精品一区二区三区四区 | 亚洲精品一区在线观看 | 欧美一区二区三区视频 | 日韩精品亚洲专区在线观看 | 91精品国产91久久久久久密臀 | 亚洲午夜视频 | 欧美另类视频在线 | 国产精品亚洲视频 | 中文字幕在线免费视频 | 爱爱爱av| 色婷婷综合久久久久中文一区二区 | 亚洲精品在线视频 | 亚洲欧洲一区二区 | 久久精品亚洲精品国产欧美 | 国产精品视频 | 精品一区二区三区在线观看 | 国产一区二区在线免费观看 | 国产aa | 午夜在线小视频 | 亚洲一区欧美 | 国产精品亚洲片在线播放 | 国产精品中文字幕一区二区三区 | 亚洲欧美激情视频 | 欧美极品视频在线观看 | 亚洲 欧美 在线 一区 | 欧美成人手机在线 | 免费观看的黄色网址 | 午夜欧美a级理论片915影院 | 久久久国产精品 |