<strike id="cy2gs"><menu id="cy2gs"></menu></strike>
  • <del id="cy2gs"><dfn id="cy2gs"></dfn></del>
  • JavaScript逐點(diǎn)突破系列之this是什么?了解完這7點(diǎn)很多疑惑都解決

    2021-4-13    前端達(dá)人

    前言

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

    了解this

    也許你在其他面向?qū)ο蟮木幊陶Z(yǔ)言曾經(jīng)看過(guò)this,也知道它會(huì)指向某個(gè)構(gòu)造器(constructor)所建立的對(duì)象。但事實(shí)上在JavaScript里面,this所代表的不僅僅是那個(gè)被建立的對(duì)象。

    先來(lái)看看ECMAScript 標(biāo)準(zhǔn)規(guī)范對(duì)this 的定義:

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

    然后再來(lái)看看MDN 對(duì)this 的定義:

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

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

    … 我想應(yīng)該不會(huì),至少我光看這兩行還是不懂。

    先來(lái)看個(gè)例子吧:

    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變性了呢,這不是我想要的結(jié)果啊,為什么呢?

    因?yàn)?code style="box-sizing:border-box;outline:0px;user-select:text !important;font-family:"font-size:14px;line-height:22px;color:#C7254E;background-color:#F9F2F4;border-radius:2px;padding:2px 4px;overflow-wrap:break-word;">getGender()返回(return)寫死了people1.gender的關(guān)系,結(jié)果自然是’female’。

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

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

    這個(gè)時(shí)候,你應(yīng)該會(huì)分別得到femalemale兩種結(jié)果。

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

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

    this到底是誰(shuí)

    看完上面的例子,還是有點(diǎn)似懂非懂吧?那接下來(lái)我們來(lái)看看不同的調(diào)用方式對(duì) this 值的影響。

    情況一:全局對(duì)象&調(diào)用普通函數(shù)

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

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

    var x = 1
    
    function fn() {
        console.log(this);   // Window 全局對(duì)象
        console.log(this.x);  // 1
    }
    
    fn(); 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    使用嚴(yán)格模式后:

    "use strict"     // 使用嚴(yán)格模式
    var x = 1
    
    function fn() {
        console.log(this);   // undefined
        console.log(this.x);  // 報(bào)錯(cuò) "Cannot read property 'x' of undefined",因?yàn)榇藭r(shí) this 是 undefined
    }
    
    fn(); 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    情況二:作為對(duì)象方法的調(diào)用

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

    如果函數(shù)作為對(duì)象的一個(gè)方法時(shí),并且作為對(duì)象的一個(gè)方法被調(diào)用時(shí),函數(shù)中的this指向這個(gè)上一級(jí)對(duì)象

    var x = 1
    var obj = {
        x: 2,
        fn: function() {
            console.log(this);    
            console.log(this.x);
        }
    }
    
    obj.fn()     
    
    // obj.fn()結(jié)果打印出;
    // Object {x: 2, fn: function}
    // 2
    
    var a = obj.fn
    a()   
    
    // a()結(jié)果打印出:   
    // Window 全局對(duì)象
    // 1 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

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

    我們?cè)賮?lái)看一個(gè)例子,如果函數(shù)被多個(gè)對(duì)象嵌套調(diào)用,this 會(huì)指向什么。

    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

    為什么結(jié)果不是 2 呢,因?yàn)樵谶@種情況下記住一句話:this 始終會(huì)指向直接調(diào)用函數(shù)的上一級(jí)對(duì)象,即 y,上面例子實(shí)際執(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

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

    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 全局對(duì)象
            }
        }
    }
    
    obj.y(); 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

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

    function fn() {
        console.log(this === obj);   // false
        console.log(this);   // Window 全局對(duì)象
    }
    
    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

    情況三:作為構(gòu)造函數(shù)調(diào)用

    我們可以使用 new 關(guān)鍵字,通過(guò)構(gòu)造函數(shù)生成一個(gè)實(shí)例對(duì)象。此時(shí),this 便指向這個(gè)新對(duì)象。

    var x = 1;
    
    function Fn() {
       this.x = 2;
        console.log(this);  // Fn {x: 2}
    }
    
    var obj = new Fn();   // obj和Fn(..)調(diào)用中的this進(jìn)行綁定
    console.log(obj.x)   // 2 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    使用new來(lái)調(diào)用Fn(..)時(shí),會(huì)構(gòu)造一個(gè)新對(duì)象并把它(obj)綁定到Fn(..)調(diào)用中的this。還有值得一提的是,如果構(gòu)造函數(shù)返回了非引用類型(string,number,boolean,null,undefined),this 仍然指向?qū)嵗男聦?duì)象。

    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

    因?yàn)镕n()返回(return)的是一個(gè)對(duì)象(引用類型),this 會(huì)指向這個(gè)return的對(duì)象。如果return的是一個(gè)非引用類型的值呢?

    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 方法調(diào)用

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

    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 全局對(duì)象
    // 1
    
    fn.apply(null)    
    // Window 全局對(duì)象
    // 1
    
    fn.call(undefined)    
    // Window 全局對(duì)象
    // 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 時(shí),如果給 this 傳的不是對(duì)象,JavaScript 會(huì)使用相關(guān)構(gòu)造函數(shù)將其轉(zhuǎn)化為對(duì)象,比如傳 number 類型,會(huì)進(jìn)行new Number()操作,如傳 string 類型,會(huì)進(jìn)行new String()操作,如傳 boolean 類型,會(huì)進(jìn)行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 的第二個(gè)及后續(xù)參數(shù)是一個(gè)參數(shù)列表,apply 的第二個(gè)參數(shù)是數(shù)組。參數(shù)列表和參數(shù)數(shù)組都將作為函數(shù)的參數(shù)進(jìn)行執(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 方法調(diào)用

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

    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 全局對(duì)象
    // 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 傳入的對(duì)象,即使是使用 call 或 apply 方法也不能改變這一事實(shí),即永久的指向 bind 傳入的第一次參數(shù)。

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

    值得一提的是,從ES6 開(kāi)始新增了箭頭函數(shù),先來(lái)看看MDN 上對(duì)箭頭函數(shù)的說(shuō)明

    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.

    這里已經(jīng)清楚了說(shuō)明了,箭頭函數(shù)沒(méi)有自己的this綁定。箭頭函數(shù)中使用的this,其實(shí)是直接包含它的那個(gè)函數(shù)或函數(shù)表達(dá)式中的this。在前面情況二中函數(shù)嵌套函數(shù)的例子中,被嵌套的函數(shù)不會(huì)繼承上層函數(shù)的 this,如果使用箭頭函數(shù),會(huì)發(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,這是因?yàn)樗鼜纳弦粚拥暮瘮?shù)中繼承了 this,你可以理解為箭頭函數(shù)修正了 this 的指向。所以箭頭函數(shù)的this不是調(diào)用的時(shí)候決定的,而是在定義的時(shí)候處在的對(duì)象就是它的this。

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

    var obj = {
      y: () => {
            console.log(this === obj);   // false
            console.log(this);           // Window 全局對(duì)象 
    
          var fn = () => {
              console.log(this === obj);   // false
              console.log(this);           // Window 全局對(duì)象 
          }
          fn();
      }
    }
    
    obj.y() 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    上例中,雖然存在兩個(gè)箭頭函數(shù),其實(shí)this取決于最外層的箭頭函數(shù),由于obj是個(gè)對(duì)象而非函數(shù),所以this指向?yàn)閃indow全局對(duì)象。

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

    var x = 1
    var obj = {
        x: 2
    }
    
    var a = () => {
        console.log(this.x)
        console.log(this)
    }
    
    a.call(obj)       
    // 1
    // Window 全局對(duì)象
    
    a.apply(obj)      
    // 1
    // Window 全局對(duì)象 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

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

    小結(jié)

    本篇文章介紹了 this 指向的幾種情況,不同的運(yùn)行環(huán)境和調(diào)用方式都會(huì)對(duì) this 產(chǎn)生影響??偟膩?lái)說(shuō),函數(shù) this 的指向取決于當(dāng)前調(diào)用該函數(shù)的對(duì)象,也就是執(zhí)行時(shí)的對(duì)象。在這一節(jié)中,你需要掌握:

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

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

    藍(lán)藍(lán)設(shè)計(jì)www.skdbbs.com )是一家專注而深入的界面設(shè)計(jì)公司,為期望卓越的國(guó)內(nèi)外企業(yè)提供卓越的UI界面設(shè)計(jì)、BS界面設(shè)計(jì) 、 cs界面設(shè)計(jì) 、 ipad界面設(shè)計(jì) 、 包裝設(shè)計(jì) 、 圖標(biāo)定制 、 用戶體驗(yàn) 、交互設(shè)計(jì)、 網(wǎng)站建設(shè) 、平面設(shè)計(jì)服務(wù)

    日歷

    鏈接

    個(gè)人資料

    存檔

    主站蜘蛛池模板: 8x福利精品第一导航| 国产99视频精品一区| 国产精品无码久久综合| 精品一区二区无码AV| 欧美日韩精品在线| 免费精品无码AV片在线观看| 久久精品国产欧美日韩| 色播精品免费小视频| 国产伦精品免编号公布| 婷婷国产成人精品一区二| 91精品婷婷国产综合久久| 99久久久精品免费观看国产| 精品无码人妻一区二区三区品| 最新国产乱人伦偷精品免费网站 | 97久人人做人人妻人人玩精品| 国产成人精品久久一区二区三区| 久久精品国产亚洲AV电影| 亚洲精品少妇30p| 亚洲?V无码成人精品区日韩| 国产一区二区精品久久凹凸| 国产精品99久久精品爆乳| 久久精品中文字幕久久| 精品久久久久久久久中文字幕| 精品熟女少妇av免费久久| 亚洲av日韩精品久久久久久a| 亚洲精品无码专区久久同性男| 免费看污污的网站欧美国产精品不卡在线观看 | 日本加勒比久久精品| 久久99精品久久久久久野外| 国产亚洲精品看片在线观看| 国产精品亚洲mnbav网站| 国产精品久操视频| 国产精品∧v在线观看| 国产精品亚洲视频| 久久亚洲精品无码观看不卡| 日韩AV毛片精品久久久| 日本国产精品久久| 亚洲精品乱码久久久久久自慰| 无码人妻精品一区二区三区东京热 | 久久精品国产清高在天天线| 嫖妓丰满肥熟妇在线精品|