秒懂 this

平常開發中常常會遇到 this 指向的 bug,鬱悶很久才猛然醒悟,痛定思痛,將 this 作個彙總,以便在往後的開發工做中少走彎路。

注意:本文講述只針對瀏覽器環境。es6

1、全局執行

console.log(this);
// Window

能夠看出在全局做用域中 this 指向當前的全局對象 Window。數組

2、函數中執行

1. 非嚴格模式中

function func () {
    console.log(this);
}
func();
// Window

2. 嚴格模式中

"use strict";
function func () {
    console.log(this);
}
func();
// undefined

3、做爲對象的方法調用

當一個函數被看成一個對象的方法調用的時候,this 指向當前的對象 obj:瀏覽器

var obj = {
    name: 'kk',
    func: function () {
        console.log(this.name);
    }
}
obj.func();
// kk

若是把對象的方法賦值給一個變量,調用該方法時,this 指向 Window:app

var obj = {
    name: 'kk',
    func: function () {
        console.log(this);
    }
}
var test = obj.func;
test();
// Window

4、做爲一個構造函數使用

在 JS 中,爲了實現類,咱們須要定義一些構造函數,在調用一個構造函數的時候加上 new 這個關鍵字:函數

function Person (name) {
    this.name = name;
    console.log(this);
}
var p1 = new Person('kk');
// Person

此時,this 指向這個構造函數調用的時候實例化出來的對象。this

固然了,構造函數其實也是一個函數,若將構造函數當作普通函數來調用,this 指向 Window:code

function Person (name) {
    this.name = name;
    console.log(this);
}
var p2 = Person('MM');
// Window

5、在定時器中使用

setInterval(function () {
    console.log(this);
}, 2000)
// Window
setTimeout(function () {
    console.log(this);
}, 0)
// Window

若是沒有特殊指向(指向更改請看下方:怎麼改變 this 的指向),setInterval 和setTimeout 的回調函數中 this 的指向都是 Window 。這是由於 JS 的定時器方法是定義在 Window 下的。對象

6、箭頭函數

1. 在全局環境中調用:

var func = () => {
    console.log(this);
}
func();
// Window

2. 做爲對象的一個函數調用:

var obj = {
    name: 'hh',
    func: function () {
       console.log(this);
    }
}
obj.func();
// obj

不難發現,普通函數做爲對象的一個函數被調用,this 指向 obj。作用域

var obj = {
    name: 'hh',
    func: () => {
       console.log(this);
    }
}
obj.func();
// Window

箭頭函數做爲對象的一個函數被調用時,若箭頭函數直接做爲對象的某個方法被調用,this 指向 Window。開發

var obj = {
    name: 'hh',
    func: function () {
       (() => {
          console.log(this);
       })()
    }
}
obj.func();
// obj

若箭頭函數在某方法的內部,this 指向箭頭函數外部非箭頭函數 this 的值;在上述示例中,this 指向 obj。

3. 特殊狀況

結合定時器調用:

var obj = {
    name: 'hh',
    func: function () {
        setTimeout(function () {
            console.log(this);
        }, 0)
    }
}
obj.func();
// Window
var obj = {
    name: 'hh',
    func: function () {
        setTimeout(() => {
            console.log(this);
        }, 0)
    }
}
obj.func();
// obj

若在對象的函數中,普通函數做爲定時器延時執行的函數調用,this 指向 Window;箭頭函數做爲定時器延時執行的函數調用, this 指向定義時所在的對象,也就是 func 中的 this,即 obj。

箭頭函數中 this 的值取決於該函數外部非箭頭函數的 this 的值,且不能經過 call() 、 apply() 和 bind() 方法來改變 this 的值。

7、call、apply、bind

call:

fun.call(thisArg[, arg1[, arg2[, ...]]])

它會當即執行函數,第一個參數是指定執行函數中 this 的上下文,後面的參數是執行函數須要傳入的參數;


apply:

fun.apply(thisArg, [argsArray])

它也會當即執行函數,第一個參數是指定執行函數中 this 的上下文,第二個參數是一個數組,是傳給執行函數的參數(與 call 的區別);


bind:

var foo = fun.bind(thisArg[, arg1[, arg2[, ...]]]);

它不會執行函數,而是返回一個新的函數,這個新的函數被指定了 this 的上下文,後面的參數是執行函數須要傳入的參數;

咱們來看個示例:

function Person(name, age) {
  this.name = name;
  this.age = age;
  console.log(this);
}
var obj = {
  name: 'kk',
  age: 6
};
Person.call(obj, 'mm', 10);
// obj,{name: "mm", age: 10}

Person.apply(obj, ['mm', 10]);
// obj,{name: "mm", age: 10}

var p1 = Person.bind(obj, 'mm', 10)
var p2 = new p1();
// Person {name: "mm", age: 10}

在這個示例中,call、apply 和 bind 的 this 都指向了 obj,都能正常運行;call、apply 會當即執行函數,call 和 apply 的區別就在於傳遞的參數,call 接收多個參數列表,apply 接收一個包含多個參數的數組;bind 不是當即執行函數,它返回一個函數,須要執行 p2 才能返回結果,bind 接收多個參數列表。

應用:怎麼改變 this 的指向

爲何講這個模塊呢,爲了便於你們更加透徹的理解上面所講述的 this 指向問題,以及更加完全的理解 JS 函數中重要的三種方法:call、apply、bind 的使用;而且在實際的項目開發中,咱們常常會遇到須要改變 this 指向的狀況。

咱們來看下都有哪些方法:

1. 使用 es6 的箭頭函數

var name = "hh";
var obj = {
    name : "kk",
    func1: function () {
        console.log(this.name)     
    },
    func2: function () {
        setTimeout(function () {
            this.func1()
        }, 1000);
    }
};

obj.func2();
// Uncaught TypeError: this.func1 is not a function

這時會報錯,由於 setTimeout 裏函數的 this 指向 Window,而 Window 對象上是沒有 func1 這個函數的。下面咱們來修改爲箭頭函數:

var name = "hh";
var obj = {
    name : "kk",
    func1: function () {
        console.log(this.name)     
    },
    func2: function () {
        setTimeout(() => {
            this.func1()
        }, 1000);
    }
};

obj.func2();
// kk

這時候,沒有報錯,由於箭頭函數的 this 的值取決於該函數外部非箭頭函數的 this 的值,也就是 func2 的 this 的值, 即 obj。

2. 在函數內部使用 _this = this

var name = "hh";
var obj = {
    name : "kk",
    func1: function () {
        console.log(this.name)     
    },
    func2: function () {
        let _this = this;
        setTimeout(function () {
            _this.func1()
        }, 1000);
    }
};

obj.func2();
// kk

此時,func2 也能正常運行。在 func2 中,首先設置 var _this = this,這裏的 this 是指向 func2 的對象 obj,爲了防止在 func2 中的 setTimeout 被 window 調用而致使的在 setTimeout 中的 this 爲 window。咱們將 this (指向變量 obj) 賦值給一個變量 _this,這樣,在 func2 中咱們使用 _this 就是指向對象 obj 了。

3. 使用 call、apply、bind

call:

var name = "hh";
var obj = {
    name : "kk",
    func1: function () {
        console.log(this.name)     
    },
    func2: function () {
        setTimeout(function () {
            this.func1()
        }.call(obj), 1000);
    }
};

obj.func2();
// kk

apply:

var name = "hh";
var obj = {
    name : "kk",
    func1: function () {
        console.log(this.name)     
    },
    func2: function () {
        setTimeout(function () {
            this.func1()
        }.apply(obj), 1000);
    }
};

obj.func2();
// kk

bind:

var name = "hh";
var obj = {
    name : "kk",
    func1: function () {
        console.log(this.name)     
    },
    func2: function () {
        setTimeout(function () {
            this.func1()
        }.bind(obj)(), 1000);
    }
};

obj.func2();
// kk

call、apply、bind 都能改變 this 的上下文對象,因此也沒有報錯,能夠正常執行。

具體緣由可看上述第七點,call、apply、bind。

4. new 實例化一個對象

如上:第四點,做爲一個構造函數使用。

相關文章
相關標籤/搜索