App下載

JavaScript 的 this 指向

若川 2021-08-26 14:42:33 瀏覽數(shù) (1938)
反饋

函數(shù)的this在調(diào)用時綁定的,完全取決于函數(shù)的調(diào)用位置(也就是函數(shù)的調(diào)用方法)。為了搞清楚this的指向是什么,必須知道相關(guān)函數(shù)是如何調(diào)用的。

全局上下文

非嚴(yán)格模式和嚴(yán)格模式中this都是指向頂層對象(瀏覽器中是window)。

this === window // true
'use strict'
this === window;
this.name = 'W3Cschool';
console.log(this.name); 

函數(shù)上下文

普通函數(shù)調(diào)用模式

// 非嚴(yán)格模式
var name = 'window';
var doSth = function(){
    console.log(this.name);
}
doSth(); // 'window'

你可能會誤以為window.doSth()是調(diào)用的,所以是指向window。雖然本例中window.doSth確實等于doSth。name等于window.name。上面代碼中這是因為在ES5中,全局變量是掛載在頂層對象(瀏覽器是window)中。 事實上,并不是如此。

// 非嚴(yán)格模式
let name2 = 'window2';
let doSth2 = function(){
    console.log(this === window);
    console.log(this.name2);
}
doSth2() // true, undefined

這個例子中l(wèi)et沒有給頂層對象中(瀏覽器是window)添加屬性,window.name2和window.doSth都是undefined。

嚴(yán)格模式中,普通函數(shù)中的this則表現(xiàn)不同,表現(xiàn)為undefined。

// 嚴(yán)格模式
'use strict'
var name = 'window';
var doSth = function(){
    console.log(typeof this === 'undefined');
    console.log(this.name);
}
doSth(); // true,// 報錯,因為this是undefined

看過的《你不知道的JavaScript》上卷的讀者,應(yīng)該知道書上將這種叫做默認(rèn)綁定。 對call,apply熟悉的讀者會類比為:

doSth.call(undefined);
doSth.apply(undefined);

效果是一樣的,call,apply作用之一就是用來修改函數(shù)中的this指向為第一個參數(shù)的。 第一個參數(shù)是undefined或者null,非嚴(yán)格模式下,是指向window。嚴(yán)格模式下,就是指向第一個參數(shù)。后文詳細(xì)解釋。經(jīng)常有這類代碼(回調(diào)函數(shù)),其實也是普通函數(shù)調(diào)用模式。

var name = 'W3Cschool';
setTimeout(function(){
    console.log(this.name);
}, 0);
// 語法
setTimeout(fn | code, 0, arg1, arg2, ...)
// 也可以是一串代碼。也可以傳遞其他函數(shù)
// 類比 setTimeout函數(shù)內(nèi)部調(diào)用fn或者執(zhí)行代碼`code`。
fn.call(undefined, arg1, arg2, ...);

對象中的函數(shù)(方法)調(diào)用模式

var name = 'window';
var doSth = function(){
    console.log(this.name);
}
var student = {
    name: 'W3Cschool',
    doSth: doSth,
    other: {
        name: 'other',
        doSth: doSth,
    }
}
student.doSth(); // 
student.other.doSth(); // 'other'
// 用call類比則為:
student.doSth.call(student);
// 用call類比則為:
student.other.doSth.call(student.other);

但往往會有以下場景,把對象中的函數(shù)賦值成一個變量了。 這樣其實又變成普通函數(shù)了,所以使用普通函數(shù)的規(guī)則(默認(rèn)綁定)。

var studentDoSth = student.doSth;
studentDoSth(); // 'window'
// 用call類比則為:
studentDoSth.call(undefined);

call、apply、bind 調(diào)用模式

上文提到call、apply,這里詳細(xì)解讀一下。先通過MDN認(rèn)識下call和apply MDN 文檔:Function.prototype.call()。

語法

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

thisArg在fun函數(shù)運行時指定的this值。需要注意的是,指定的this值并不一定是該函數(shù)執(zhí)行時真正的this值,如果這個函數(shù)處于非嚴(yán)格模式下,則指定為null和undefined的this值會自動指向全局對象(瀏覽器中就是window對象),同時值為原始值(數(shù)字,字符串,布爾值)的this會指向該原始值的自動包裝對象。arg1, arg2, ...指定的參數(shù)列表返回值返回值是你調(diào)用的方法的返回值,若該方法沒有返回值,則返回undefined。apply和call類似。只是參數(shù)不一樣。它的參數(shù)是數(shù)組(或者類數(shù)組)。

根據(jù)參數(shù)thisArg的描述,可以知道,call就是改變函數(shù)中的this指向為thisArg,并且執(zhí)行這個函數(shù),這也就使 JavaScript 靈活很多。嚴(yán)格模式下,thisArg是原始值是值類型,也就是原始值。不會被包裝成對象。舉個例子:

var doSth = function(name){
    console.log(this);
    console.log(name);
}
doSth.call(2, 'W3Cschool'); // Number{2}, 'W3Cschool'
var doSth2 = function(name){
    'use strict';
    console.log(this);
    console.log(name);
}
doSth2.call(2, 'W3Cschool'); // 2, 'W3Cschool 你'

雖然一般不會把thisArg參數(shù)寫成值類型。但還是需要知道這個知識。 之前寫過一篇文章:面試官問:能否模擬實現(xiàn)JS的call和apply方法 就是利用對象上的函數(shù)this指向這個對象,來模擬實現(xiàn)call和apply的。感興趣的讀者思考如何實現(xiàn),再去看看筆者的實現(xiàn)。

bind和call和apply類似,第一個參數(shù)也是修改this指向,只不過返回值是新函數(shù),新函數(shù)也能當(dāng)做構(gòu)造函數(shù)(new)調(diào)用。 MDN Function.prototype.bind

bind()方法創(chuàng)建一個新的函數(shù), 當(dāng)這個新函數(shù)被調(diào)用時this鍵值為其提供的值,其參數(shù)列表前幾項值為創(chuàng)建時指定的參數(shù)序列。語法: fun.bind(thisArg[, arg1[, arg2[, ...]]])參數(shù): thisArg 調(diào)用綁定函數(shù)時作為this參數(shù)傳遞給目標(biāo)函數(shù)的值。 如果使用new運算符構(gòu)造綁定函數(shù),則忽略該值。當(dāng)使用bind在setTimeout中創(chuàng)建一個函數(shù)(作為回調(diào)提供)時,作為thisArg傳遞的任何原始值都將轉(zhuǎn)換為object。如果沒有提供綁定的參數(shù),則執(zhí)行作用域的this被視為新函數(shù)的thisArg。 arg1, arg2, ... 當(dāng)綁定函數(shù)被調(diào)用時,這些參數(shù)將置于實參之前傳遞給被綁定的方法。 返回值 返回由指定的this值和初始化參數(shù)改造的原函數(shù)拷貝。

之前也寫過一篇文章:如何模擬實現(xiàn) JS 的 bind 方法,就是利用call和apply指向這個thisArg參數(shù),來模擬實現(xiàn)bind的。感興趣的讀者思考如何實現(xiàn),再去看看筆者的實現(xiàn)。

構(gòu)造函數(shù)調(diào)用模式

function Student(name){
    this.name = name;
    console.log(this); // {name: 'W3Cschool'}
    // 相當(dāng)于返回了
    // return this;
}
var result = new Student('W3Cschool');

使用new操作符調(diào)用函數(shù),會自動執(zhí)行以下步驟。

  1. 創(chuàng)建了一個全新的對象。
  2. 這個對象會被執(zhí)行[[Prototype]](也就是__proto__)鏈接。
  3. 生成的新對象會綁定到函數(shù)調(diào)用的this。
  4. 通過new創(chuàng)建的每個對象將最終被[[Prototype]]鏈接到這個函數(shù)的prototype對象上。
  5. 如果函數(shù)沒有返回對象類型Object(包含F(xiàn)unctoin, Array, Date, RegExg, Error),那么new表達(dá)式中的函數(shù)調(diào)用會自動返回這個新的對象。

由此可以知道:new操作符調(diào)用時,this指向生成的新對象。 特別提醒一下,new調(diào)用時的返回值,如果沒有顯式返回對象或者函數(shù),才是返回生成的新對象。

function Student(name){
    this.name = name;
    // return function f(){};
    // return {};
}
var result = new Student('W3Cschool');
console.log(result); {name: 'W3Cschool'}
// 如果返回函數(shù)f,則result是函數(shù)f,如果是對象{},則result是對象{}

很多人或者文章都忽略了這一點,直接簡單用typeof判斷對象。雖然實際使用時不會顯示返回,但面試官會問到。

之前也寫了一篇文章面試官問:能否模擬實現(xiàn)JS的new操作符,是使用apply來把this指向到生成的新生成的對象上。感興趣的讀者思考如何實現(xiàn),再去看看筆者的實現(xiàn)。

原型鏈中的調(diào)用模式

function Student(name){
    this.name = name;
}
var s1 = new Student('W3Cschool');
Student.prototype.doSth = function(){
    console.log(this.name);
}
s1.doSth(); // 'W3Cschool'

會發(fā)現(xiàn)這個似曾相識。這就是對象上的方法調(diào)用模式。自然是指向生成的新對象。 如果該對象繼承自其它對象。同樣會通過原型鏈查找。 上面代碼使用 ES6中class寫法則是:

class Student{
    constructor(name){
        this.name = name;
    }
    doSth(){
        console.log(this.name);
    }
}
let s1 = new Student('若川');
s1.doSth();

babel es6轉(zhuǎn)換成es5的結(jié)果,可以去babeljs網(wǎng)站轉(zhuǎn)換測試自行試試。

'use strict';

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Student = function () {
    function Student(name) {
        _classCallCheck(this, Student);

        this.name = name;
    }

    _createClass(Student, [{
        key: 'doSth',
        value: function doSth() {
            console.log(this.name);
        }
    }]);

    return Student;
}();

var s1 = new Student('W3Cschool');
s1.doSth();

由此看出,ES6的class也是通過構(gòu)造函數(shù)模擬實現(xiàn)的,是一種語法糖。

箭頭函數(shù)調(diào)用模式

先看箭頭函數(shù)和普通函數(shù)的重要區(qū)別:

1、沒有自己的this、super、arguments和new.target綁定。 2、不能使用new來調(diào)用。 3、沒有原型對象。 4、不可以改變this的綁定。 5、形參名稱不能重復(fù)。

箭頭函數(shù)中沒有this綁定,必須通過查找作用域鏈來決定其值。 如果箭頭函數(shù)被非箭頭函數(shù)包含,則this綁定的是最近一層非箭頭函數(shù)的this,否則this的值則被設(shè)置為全局對象。 比如:

var name = 'window';
var student = {
    name: 'W3Cschool',
    doSth: function(){
        // var self = this;
        var arrowDoSth = () => {
            // console.log(self.name);
            console.log(this.name);
        }
        arrowDoSth();
    },
    arrowDoSth2: () => {
        console.log(this.name);
    }
}
student.doSth(); // 'W3Cschool'
student.arrowDoSth2(); // 'window'

其實就是相當(dāng)于箭頭函數(shù)外的this是緩存的該箭頭函數(shù)上層的普通函數(shù)的this。如果沒有普通函數(shù),則是全局對象(瀏覽器中則是window)。 也就是說無法通過call、apply、bind綁定箭頭函數(shù)的this(它自身沒有this)。而call、apply、bind可以綁定緩存箭頭函數(shù)上層的普通函數(shù)的this。 比如:

var student = {
    name: 'W3Cschool',
    doSth: function(){
        console.log(this.name);
        return () => {
            console.log('arrowFn:', this.name);
        }
    }
}
var person = {
    name: 'person',
}
student.doSth().call(person); // 'W3Cschool'  'arrowFn:' 'W3Cschool'
student.doSth.call(person)(); // 'person' 'arrowFn:' 'person'

DOM事件處理函數(shù)調(diào)用

addEventerListener、attachEvent、onclick

<button class="button">onclick</button>
<ul class="list">
    <li>1</li>
    <li>2</li>
    <li>3</li>
</ul>
<script>
    var button = document.querySelector('button');
    button.onclick = function(ev){
        console.log(this);
        console.log(this === ev.currentTarget); // true
    }
    var list = document.querySelector('.list');
    list.addEventListener('click', function(ev){
        console.log(this === list); // true
        console.log(this === ev.currentTarget); // true
        console.log(this);
        console.log(ev.target);
    }, false);
</script>

onclick和addEventerListener是指向綁定事件的元素。 一些瀏覽器,比如IE6~IE8下使用attachEvent,this指向是window。 順便提下:面試官也經(jīng)常考察ev.currentTarget和ev.target的區(qū)別。 ev.currentTarget是綁定事件的元素,而ev.target是當(dāng)前觸發(fā)事件的元素。比如這里的分別是ul和li。 但也可能點擊的是ul,這時ev.currentTarget和ev.target就相等了。

內(nèi)聯(lián)事件處理函數(shù)調(diào)用

<button class="btn1" onclick="console.log(this === document.querySelector('.btn1'))">點我呀</button>
<button onclick="console.log((function(){return this})());">再點我呀</button>

第一個是button本身,所以是true,第二個是window。這里跟嚴(yán)格模式?jīng)]有關(guān)系。 當(dāng)然我們現(xiàn)在不會這樣用了,但有時不小心寫成了這樣,也需要了解。

其實this的使用場景還有挺多,比如對象object中的getter、setter的this,new Function()、eval。 但掌握以上幾種,去分析其他的,就自然迎刃而解了。 使用比較多的還是普通函數(shù)調(diào)用、對象的函數(shù)調(diào)用、new調(diào)用、call、apply、bind調(diào)用、箭頭函數(shù)調(diào)用。 那么他們的優(yōu)先級是怎樣的呢。

優(yōu)先級

而箭頭函數(shù)的this是上層普通函數(shù)的this或者是全局對象(瀏覽器中是window),所以排除,不算優(yōu)先級。

var name = 'window';
var person = {
    name: 'person',
}
var doSth = function(){
    console.log(this.name);
    return function(){
        console.log('return:', this.name);
    }
}
var Student = {
    name: 'W3Cschool',
    doSth: doSth,
}
// 普通函數(shù)調(diào)用
doSth(); // window
// 對象上的函數(shù)調(diào)用
Student.doSth(); // 'W3Cschool'
// call、apply 調(diào)用
Student.doSth.call(person); // 'person'
new Student.doSth.call(person);

試想一下,如果是Student.doSth.call(person)先執(zhí)行的情況下,那new執(zhí)行一個函數(shù)。是沒有問題的。 然而事實上,這代碼是報錯的。運算符優(yōu)先級是new比點號低,所以是執(zhí)行new (Student.doSth.call)(person) 而Function.prototype.call,雖然是一個函數(shù)(apply、bind也是函數(shù)),跟箭頭函數(shù)一樣,不能用new調(diào)用。所以報錯了。

Uncaught TypeError: Student.doSth.call is not a constructor

這是因為函數(shù)內(nèi)部有兩個不同的方法:[[Call]]和[[Constructor]]。 當(dāng)使用普通函數(shù)調(diào)用時,[[Call]]會被執(zhí)行。當(dāng)使用構(gòu)造函數(shù)調(diào)用時,[[Constructor]]會被執(zhí)行。call、apply、bind和箭頭函數(shù)內(nèi)部沒有[[Constructor]]方法。

從上面的例子可以看出普通函數(shù)調(diào)用優(yōu)先級最低,其次是對象上的函數(shù)。 call(apply、bind)調(diào)用方式和new調(diào)用方式的優(yōu)先級,在《你不知道的JavaScript》是對比bind和new,引用了mdn的bind的ployfill實現(xiàn),new調(diào)用時bind之后的函數(shù),會忽略bind綁定的第一個參數(shù),(mdn的實現(xiàn)其實還有一些問題,感興趣的讀者,可以看我之前的文章:面試官問:能否模擬實現(xiàn)JS的bind方法),說明new的調(diào)用的優(yōu)先級最高。 所以它們的優(yōu)先級是new 調(diào)用 > call、apply、bind 調(diào)用 > 對象上的函數(shù)調(diào)用 > 普通函數(shù)調(diào)用。

總結(jié)

如果要判斷一個運行中函數(shù)的 this 綁定, 就需要找到這個函數(shù)的直接調(diào)用位置。 找到之后 就可以順序應(yīng)用下面這四條規(guī)則來判斷 this 的綁定對象。

  1. new 調(diào)用:綁定到新創(chuàng)建的對象,注意:顯示return函數(shù)或?qū)ο螅祷刂挡皇切聞?chuàng)建的對象,而是顯式返回的函數(shù)或?qū)ο蟆?/li>
  2. call 或者 apply( 或者 bind) 調(diào)用:嚴(yán)格模式下,綁定到指定的第一個參數(shù)。非嚴(yán)格模式下,null和undefined,指向全局對象(瀏覽器中是window),其余值指向被new Object()包裝的對象。
  3. 對象上的函數(shù)調(diào)用:綁定到那個對象。
  4. 普通函數(shù)調(diào)用: 在嚴(yán)格模式下綁定到 undefined,否則綁定到全局對象。

ES6 中的箭頭函數(shù):不會使用上文的四條標(biāo)準(zhǔn)的綁定規(guī)則, 而是根據(jù)當(dāng)前的詞法作用域來決定this, 具體來說, 箭頭函數(shù)會繼承外層函數(shù),調(diào)用的 this 綁定( 無論 this 綁定到什么),沒有外層函數(shù),則是綁定到全局對象(瀏覽器中是window)。 這其實和 ES6 之前代碼中的 self = this 機制一樣。

DOM事件函數(shù):一般指向綁定事件的DOM元素,但有些情況綁定到全局對象(比如IE6~IE8的attachEvent)。

一定要注意,有些調(diào)用可能在無意中使用普通函數(shù)綁定規(guī)則。 如果想“ 更安全” 地忽略 this 綁 定, 你可以使用一個對象, 比如? = Object.create(null), 以保護(hù)全局對象。

面試官考察this指向就可以考察new、call、apply、bind,箭頭函數(shù)等用法。從而擴展到作用域、閉包、原型鏈、繼承、嚴(yán)格模式等。這就是面試官樂此不疲的原因。


0 人點贊