JavaScript逐點突破系列之this是什么?了解完這7點很多疑惑都解決

2021-4-13    前端達人

前言

本章將專門介紹與執(zhí)行上下文創(chuàng)建階段直接相關的最后一個細節(jié)——this是什么?以及它的指向到底是什么。

了解this

也許你在其他面向對象的編程語言曾經看過this,也知道它會指向某個構造器(constructor)所建立的對象。但事實上在JavaScript里面,this所代表的不僅僅是那個被建立的對象。

先來看看ECMAScript 標準規(guī)范對this 的定義:

「The this keyword evaluates to the value of the ThisBinding of the current execution context.」
「this 這個關鍵字代表的值為當前執(zhí)行上下文的ThisBinding。」

然后再來看看MDN 對this 的定義:

「In most cases, the value of this is determined by how a function is called.」
「在大多數(shù)的情況下,this 其值取決于函數(shù)的調用方式?!?

好,如果上面兩行就看得懂的話那么就不用再往下看了,Congratulations!

… 我想應該不會,至少我光看這兩行還是不懂。

先來看個例子吧:

var getGender = function() {
    return people1.gender;
};

var people1 = {
    gender: 'female',
    getGender: getGender
};

var people2 = {
    gender: 'male',
    getGender: getGender
};

console.log(people1.getGender());    // female
console.log(people2.getGender());    // female 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

what?怎么people2變性了呢,這不是我想要的結果啊,為什么呢?

因為getGender()返回(return)寫死了people1.gender的關系,結果自然是’female’。

那么,如果我們把getGender稍改一下:

var getGender = function() {
    return this.gender;
}; 
  • 1
  • 2
  • 3
  • 4

這個時候,你應該會分別得到femalemale兩種結果。

所以回到前面講的重點,從這個例子可以看出,即便people1people2getGender方法參照的都是同一個getGender function,但由于調用的對象不同,所以執(zhí)行的結果也會不同

現(xiàn)在我們知道了第一個重點,**this實際上是在函數(shù)被調用時發(fā)生的綁定,它指向什么完全取決于函數(shù)的調用方式。**如何的區(qū)分this呢?

this到底是誰

看完上面的例子,還是有點似懂非懂吧?那接下來我們來看看不同的調用方式對 this 值的影響。

情況一:全局對象&調用普通函數(shù)

在全局環(huán)境中,this 指向全局對象,在瀏覽器中,它就是 window 對象。下面的示例中,無論是否是在嚴格模式下,this 都是指向全局對象。

var x = 1

console.log(this.x)               // 1
console.log(this.x === x)         // true
console.log(this === window)      // true 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

如果普通函數(shù)是在全局環(huán)境中被調用,在非嚴格模式下,普通函數(shù)中 this 也指向全局對象;如果是在嚴格模式下,this 將會是 undefined。ES5 為了使 JavaScript 運行在更有限制性的環(huán)境而添加了嚴格模式,嚴格模式為了消除安全隱患,禁止了 this 關鍵字指向全局對象。

var x = 1

function fn() {
    console.log(this);   // Window 全局對象
    console.log(this.x);  // 1
}

fn(); 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

使用嚴格模式后:

"use strict"     // 使用嚴格模式
var x = 1

function fn() {
    console.log(this);   // undefined
    console.log(this.x);  // 報錯 "Cannot read property 'x' of undefined",因為此時 this 是 undefined
}

fn(); 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

情況二:作為對象方法的調用

我們知道,在對象里的值如果是原生值(primitive type;例如,字符串、數(shù)值、布爾值),我們會把這個新建立的東西稱為「屬性(property)」;如果對象里面的值是函數(shù)(function)的話,我們則會把這個新建立的東西稱為「方法(method)」。

如果函數(shù)作為對象的一個方法時,并且作為對象的一個方法被調用時,函數(shù)中的this指向這個上一級對象。

var x = 1
var obj = {
    x: 2,
    fn: function() {
        console.log(this);    
        console.log(this.x);
    }
}

obj.fn()     

// obj.fn()結果打印出;
// Object {x: 2, fn: function}
// 2

var a = obj.fn
a()   

// a()結果打印出:   
// Window 全局對象
// 1 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

在上面的例子中,直接運行 obj.fn() ,調用該函數(shù)的上一級對象是 obj,所以 this 指向 obj,得到 this.x 的值是 2;之后我們將 fn 方法首先賦值給變量 a,a 運行在全局環(huán)境中,所以此時 this 指向全局對象Window,得到 this.x 為 1。

我們再來看一個例子,如果函數(shù)被多個對象嵌套調用,this 會指向什么。

var x = 1
var obj = {
  x: 2,
  y: {
    x: 3,
    fn: function() {
      console.log(this);   // Object {x: 3, fn: function}
      console.log(this.x);   // 3
    }
  }
}

obj.y.fn(); 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

為什么結果不是 2 呢,因為在這種情況下記住一句話:this 始終會指向直接調用函數(shù)的上一級對象,即 y,上面例子實際執(zhí)行的是下面的代碼。

var y = {
  x: 3,
  fn: function() {
    console.log(this);   // Object {x: 3, fn: function}
    console.log(this.x);   // 3
  }
}

var x = 1
var obj = {
  x: 2,
  y: y
}

obj.y.fn(); 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

對象可以嵌套,函數(shù)也可以,如果函數(shù)嵌套,this 會有變化嗎?我們通過下面代碼來探討一下。

var obj = {
    y: function() {
        console.log(this === obj);   // true
        console.log(this);   // Object {y: function}
        fn();

        function fn() {
            console.log(this === obj);   // false
            console.log(this);   // Window 全局對象
        }
    }
}

obj.y(); 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

在函數(shù) y 中,this 指向了調用它的上一級對象 obj,這是沒有問題的。但是在嵌套函數(shù) fn 中,this 并不指向 obj。嵌套的函數(shù)不會從調用它的函數(shù)中繼承 this,當嵌套函數(shù)作為函數(shù)調用時,其 this 值在非嚴格模式下指向全局對象,在嚴格模式是 undefined,所以上面例子實際執(zhí)行的是下面的代碼。

function fn() {
    console.log(this === obj);   // false
    console.log(this);   // Window 全局對象
}

var obj = {
    y: function() {
        console.log(this === obj);   // true
        console.log(this);   // Object {y: function}
        fn();
    }
}

obj.y(); 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

情況三:作為構造函數(shù)調用

我們可以使用 new 關鍵字,通過構造函數(shù)生成一個實例對象。此時,this 便指向這個新對象。

var x = 1;

function Fn() {
   this.x = 2;
    console.log(this);  // Fn {x: 2}
}

var obj = new Fn();   // obj和Fn(..)調用中的this進行綁定
console.log(obj.x)   // 2 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

使用new來調用Fn(..)時,會構造一個新對象并把它(obj)綁定到Fn(..)調用中的this。還有值得一提的是,如果構造函數(shù)返回了非引用類型(string,number,boolean,null,undefined),this 仍然指向實例化的新對象。

var x = 1

function Fn() {
  this.x = 2

  return {
    x: 3
  }
}

var a = new Fn()

console.log(a.x)      // 3 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

因為Fn()返回(return)的是一個對象(引用類型),this 會指向這個return的對象。如果return的是一個非引用類型的值呢?

var x = 1

function Fn() {
  this.x = 2

  return 3
}

var a = new Fn()

console.log(a.x)      // 2 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

情況四:call 和 apply 方法調用

如果你想改變 this 的指向,可以使用 call 或 apply 方法。它們的第一個參數(shù)都是指定函數(shù)運行時其中的this指向。如果第一個參數(shù)不傳(參數(shù)為空)或者傳 null 、undefined,默認 this 指向全局對象(非嚴格模式)或 undefined(嚴格模式)。

var x = 1;

var obj = {
  x: 2
}

function fn() {
    console.log(this);
    console.log(this.x);
}

fn.call(obj)
// Object {x: 2}
// 2

fn.apply(obj)     
// Object {x: 2}
// 2

fn.call()         
// Window 全局對象
// 1

fn.apply(null)    
// Window 全局對象
// 1

fn.call(undefined)    
// Window 全局對象
// 1 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

使用 call 和 apply 時,如果給 this 傳的不是對象,JavaScript 會使用相關構造函數(shù)將其轉化為對象,比如傳 number 類型,會進行new Number()操作,如傳 string 類型,會進行new String()操作,如傳 boolean 類型,會進行new Boolean()操作。

function fn() {
  console.log(Object.prototype.toString.call(this))
}

fn.call('love')      // [object String]
fn.apply(1)          // [object Number]
fn.call(true)          // [object Boolean] 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

call 和 apply 的區(qū)別在于,call 的第二個及后續(xù)參數(shù)是一個參數(shù)列表,apply 的第二個參數(shù)是數(shù)組。參數(shù)列表和參數(shù)數(shù)組都將作為函數(shù)的參數(shù)進行執(zhí)行。

var x = 1

var obj = {
  x: 2
}

function Sum(y, z) {
  console.log(this.x + y + z)
}

Sum.call(obj, 3, 4)       // 9
Sum.apply(obj, [3, 4])    // 9 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

情況五:bind 方法調用

調用 f.bind(someObject) 會創(chuàng)建一個與 f 具有相同函數(shù)體和作用域的函數(shù),但是在這個新函數(shù)中,新函數(shù)的 this 會永久的指向 bind 傳入的第一個參數(shù),無論這個函數(shù)是如何被調用的。

var x = 1

var obj1 = {
    x: 2
};
var obj2 = {
    x: 3
};

function fn() {
    console.log(this);
    console.log(this.x);
};

var a = fn.bind(obj1);
var b = a.bind(obj2);

fn();
// Window 全局對象
// 1

a();
// Object {x: 2}
// 2

b();
// Object {x: 2}
// 2

a.call(obj2);
// Object {x: 2}
// 2 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33

在上面的例子中,雖然我們嘗試給函數(shù) a 重新指定 this 的指向,但是它依舊指向第一次 bind 傳入的對象,即使是使用 call 或 apply 方法也不能改變這一事實,即永久的指向 bind 傳入的第一次參數(shù)。

情況六:箭頭函數(shù)中this指向

值得一提的是,從ES6 開始新增了箭頭函數(shù),先來看看MDN 上對箭頭函數(shù)的說明

An arrow function expression has a shorter syntax than a function expression and does notbind its ownthis,arguments,super, ornew.target. Arrow functions are always anonymous. These function expressions are best suited for non-method functions, and they cannot be used as constructors.

這里已經清楚了說明了,箭頭函數(shù)沒有自己的this綁定。箭頭函數(shù)中使用的this,其實是直接包含它的那個函數(shù)或函數(shù)表達式中的this。在前面情況二中函數(shù)嵌套函數(shù)的例子中,被嵌套的函數(shù)不會繼承上層函數(shù)的 this,如果使用箭頭函數(shù),會發(fā)生什么變化呢?

var obj = {
  y: function() {
        console.log(this === obj);   // true
        console.log(this);           // Object {y: function}

      var fn = () => {
          console.log(this === obj);   // true
          console.log(this);           // Object {y: function}
      }
      fn();
  }
}

obj.y() 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

和普通函數(shù)不一樣,箭頭函數(shù)中的 this 指向了 obj,這是因為它從上一層的函數(shù)中繼承了 this,你可以理解為箭頭函數(shù)修正了 this 的指向。所以箭頭函數(shù)的this不是調用的時候決定的,而是在定義的時候處在的對象就是它的this

換句話說,箭頭函數(shù)的this看外層的是否有函數(shù),如果有,外層函數(shù)的this就是內部箭頭函數(shù)的this,如果沒有,則this是window。

var obj = {
  y: () => {
        console.log(this === obj);   // false
        console.log(this);           // Window 全局對象 

      var fn = () => {
          console.log(this === obj);   // false
          console.log(this);           // Window 全局對象 
      }
      fn();
  }
}

obj.y() 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

上例中,雖然存在兩個箭頭函數(shù),其實this取決于最外層的箭頭函數(shù),由于obj是個對象而非函數(shù),所以this指向為Window全局對象。

同 bind 一樣,箭頭函數(shù)也很“頑固”,我們無法通過 call 和 apply 來改變 this 的指向,即傳入的第一個參數(shù)被忽略。

var x = 1
var obj = {
    x: 2
}

var a = () => {
    console.log(this.x)
    console.log(this)
}

a.call(obj)       
// 1
// Window 全局對象

a.apply(obj)      
// 1
// Window 全局對象 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

上面的文字描述過多可能有點干澀,那么就看以下的這張流程圖吧,我覺得這個圖總結的很好,圖中的流程只針對于單個規(guī)則。

小結

本篇文章介紹了 this 指向的幾種情況,不同的運行環(huán)境和調用方式都會對 this 產生影響。總的來說,函數(shù) this 的指向取決于當前調用該函數(shù)的對象,也就是執(zhí)行時的對象。在這一節(jié)中,你需要掌握:

  • this 指向全局對象的情況;
  • 嚴格模式和非嚴格模式下 this 的區(qū)別;
  • 函數(shù)作為對象的方法調用時 this 指向的幾種情況;
  • 作為構造函數(shù)時 this 的指向,以及是否 return 的區(qū)別;
  • 使用 call 和 apply 改變調用函數(shù)的對象;
  • bind 創(chuàng)建的函數(shù)中 this 的指向;

  • 箭頭函數(shù)中的 this 指向。
  • 轉自:csdn 論壇  作者:蛋黃酥要不要來一口阿

藍藍設計www.bouu.cn )是一家專注而深入的界面設計公司,為期望卓越的國內外企業(yè)提供卓越的UI界面設計、BS界面設計 、 cs界面設計 、 ipad界面設計 、 包裝設計 、 圖標定制 、 用戶體驗 、交互設計、 網站建設 、平面設計服

分享本文至:

日歷

鏈接

個人資料

藍藍設計的小編 http://www.bouu.cn

存檔