JavaScript如何改變this指向?下面本篇文章給大家介紹一下JS改變this指向的三種方法,希望對大家有所幫助!
前端(vue)入門到精通課程:進入學(xué)習(xí)
一、this指向
點擊打開視頻講解更加詳細
this隨處可見,一般誰調(diào)用,this就指向誰。this在不同環(huán)境下,不同作用下,表現(xiàn)的也不同。
以下幾種情況,this都是指向window
1、全局作用下,this指向的是window
console.log(window); console.log(this); console.log(window == this); // true
2、函數(shù)獨立調(diào)用時,函數(shù)內(nèi)部的this也指向window
function fun() { console.log('我是函數(shù)體'); console.log(this); // Window } fun();
3、被嵌套的函數(shù)獨立調(diào)用時,this默認指向了window
function fun1() { function fun2() { console.log('我是嵌套函數(shù)'); console.log(this); // Window } fun2(); } fun1();
4、自調(diào)執(zhí)行函數(shù)(立即執(zhí)行)中內(nèi)部的this也是指向window
(function() { console.log('立即執(zhí)行'); console.log(this); // Window })()
需要額外注意的是:
- 構(gòu)造函數(shù)中的this,用于給類定義成員(屬性和方法)
- 箭頭函數(shù)中沒有this指向,如果在箭頭函數(shù)中有,則會向上一層函數(shù)中查找this,直到window
二、改變this指向
1、call() 方法
call() 方法的第一個參數(shù)必須是指定的對象,然后方法的原參數(shù),挨個放在后面。 (1)第一個參數(shù):傳入該函數(shù)this執(zhí)行的對象,傳入什么強制指向什么; (2)第二個參數(shù)開始:將原函數(shù)的參數(shù)往后順延一位
用法: 函數(shù)名.call()
function fun() { console.log(this); // 原來的函數(shù)this指向的是 Window } fun(); function fun(a, b) { console.log(this); // this指向了輸入的 字符串call console.log(a + b); } //使用call() 方法改變this指向,此時第一個參數(shù)是 字符串call,那么就會指向字符串call fun.call('call', 2, 3) // 后面的參數(shù)就是原來函數(shù)自帶的實參
2、apply() 方法
apply() 方法的第一個參數(shù)是指定的對象,方法的原參數(shù),統(tǒng)一放在第二個數(shù)組參數(shù)中。 (1)第一個參數(shù):傳入該函數(shù)this執(zhí)行的對象,傳入什么強制指向什么; (2)第二個參數(shù)開始:將原函數(shù)的參數(shù)放在一個數(shù)組中
用法: 函數(shù)名.apply()
function fun() { console.log(this); // 原來的函數(shù)this指向的是 Window } fun(); function fun(a, b) { console.log(this); // this指向了輸入的 字符串a(chǎn)pply console.log(a + b); } //使用apply() 方法改變this指向,此時第一個參數(shù)是 字符串a(chǎn)pply,那么就會指向字符串a(chǎn)pply fun.apply('apply', [2, 3]) // 原函數(shù)的參數(shù)要以數(shù)組的形式呈現(xiàn)
3、bind() 方法
bind() 方法的用法和call()一樣,直接運行方法,需要注意的是:bind返回新的方法,需要重新 調(diào)用 是需要自己手動調(diào)用的
用法: 函數(shù)名.bind()
function fun() { console.log(this); // 原來的函數(shù)this指向的是 Window } fun(); function fun(a, b) { console.log(this); // this指向了輸入的 字符串bind console.log(a + b); } //使用bind() 方法改變this指向,此時第一個參數(shù)是 字符串bind,那么就會指向字符串bind let c = fun.bind('bind', 2, 3); c(); // 返回新的方法,需要重新調(diào)用 // 也可以使用下面兩種方法進行調(diào)用 // fun.bind('bind', 2, 3)(); // fun.bind('bind')(2, 3);
【