javascript的this

一:全局執行

  1. 瀏覽器
console.log(this);
// Window
  1. node
console.log(this);
// global

總結:可以看出在全局作用域中 this 指向當前的全局對象(瀏覽器端是 Window,node 中是 global)。

二:函數中執行

  1. 非嚴格模式中
function func () {
    console.log(this);
}
func();
// Window
  1. 嚴格模式中
"use strict";
function func () {
    console.log(this);
}
func();
// undefined

三:作爲對象的方法調用
1.當一個函數被當作一個對象的方法調用的時候,this 指向當前的對象 obj:

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

2.如果把對象的方法賦值給一個變量,調用該方法時,this 指向 Window:

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

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

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

此時,this 指向這個構造函數調用的時候實例化出來的對象。
當然了,構造函數其實也是一個函數,若將構造函數當做普通函數來調用,this 指向 Window:

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

五:在定時器中使用

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

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

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

六:箭頭函數

1.在全局環境中調用:

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

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

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 的值。

七:call、apply、bind
1.call

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

它會立即執行函數,第一個參數是指定執行函數中 this 的上下文,後面的參數是執行函數需要傳入的參數;
2.apply:

fun.apply(thisArg, [argsArray])

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

3.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
1.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

2.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

3.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。

  1. new 實例化一個對象
    如上:第四點,作爲一個構造函數使用。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章