JavaScript 中的 this ,看著一篇就夠了
在 js 中,this 這個上下文總是變化莫測,很多時候出現 bug 總是一頭霧水,其實,只要分清楚不同的情況下如何執行就 ok 了。
全局執行
首先,我們在全局環境中看看它的 this 是什么:
first. 瀏覽器:
console.log(this);
// Window {speechSynthesis: SpeechSynthesis, caches: CacheStorage, localStorage: Storage, sessionStorage: Storage, webkitStorageInfo: DeprecatedStorageInfo…}
可以看到打印出了 window 對象;
second. node:
console.log(this);
// global
可以看到打印出了 global 對象;
總結:在全局作用域中它的 this 執行當前的全局對象(瀏覽器端是 Window,node 中是 global)。
函數中執行
純粹的函數調用
這是最普通的函數使用方法了:
function test() {
console.log(this);
};
test();
// Window {speechSynthesis: SpeechSynthesis, caches: CacheStorage, localStorage: Storage, sessionStorage: Storage, webkitStorageInfo: DeprecatedStorageInfo…}
我們可以看到,一個函數被直接調用的時候,屬于全局調用,這時候它的 this 指向 全局對象;
嚴格模式 ‘use strict’;
如果在嚴格模式的情況下執行純粹的函數調用,那么這里的的 this 并不會指向全局,而是 undefined,這樣的做法是為了消除 js 中一些不嚴謹的行為:
'use strict';
function test() {
console.log(this);
};
test();
// undefined
當然,把它放在一個立即執行函數中會更好,避免了污染全局:
(function (){
"use strict";
console.log(this);
})();
// undefined
作為對象的方法調用
當一個函數被當作一個對象的方法調用的時候:
var obj = {
name: 'qiutc',
foo: function() {
console.log(this.name);
}
}
obj.foo();
// 'qiutc'
這時候,this 指向當前的這個對象;
當然,我們還可以這么做:
function test() {
console.log(this.name);
}
var obj = {
name: 'qiutc',
foo: test
}
obj.foo();
// 'qiutc'
同樣不變,因為在 js 中一切都是對象,函數也是一個對象,對于 test ,它只是一個函數名,函數的引用,它指向這個函數,當 foo = test,foo 同樣也指向了這個函數。
如果把對象的方法賦值給一個變量,然后直接調用這個變量呢:
var obj = {
name: 'qiutc',
foo: function() {
console.log(this);
}
}
var test = obj.foo;
test();
// Window
可以看到,這時候 this 執行了全局,當我們把 test = obj.foo ,test 直接指向了一個函數的引用,這時候,其實和 obj 這個對象沒有關系了,所以,它是被當作一個普通函數來直接調用,因此,this 指向全局對象。
一些坑
我們經常在回調函數里面會遇到一些坑:
var obj = {
name: 'qiutc',
foo: function() {
console.log(this);
},
foo2: function() {
console.log(this); //Object {name: "qiutc"...}
setTimeout(this.foo, 1000); // window 對象
}
}
obj.foo2();
執行這段代碼我們會發現兩次打印出來的 this 是不一樣的:
第一次是 foo2 中直接打印 this,這里指向 obj 這個對象,我們毋庸置疑;
但是在 setTimeout 中執行的 this.foo,卻指向了全局對象,這里不是把它當作函數的方法使用嗎?這一點經常讓很多初學者疑惑;
其實,setTimeout 也只是一個函數而已,函數必然有可能需要參數,我們把 this.foo 當作一個參數傳給 setTimeout 這個函數,就像它需要一個 fun 參數,在傳入參數的時候,其實做了個這樣的操作 fun = this.foo,看到沒有,這里我們直接把 fun 指向 this.foo 的引用;執行的時候其實是執行了 fun() 所以已經和 obj 無關了,它是被當作普通函數直接調用的,因此 this 指向全局對象。
這個問題是很多異步回調函數中普遍會碰到的;
解決
為了解決這個問題,我們可以利用 閉包 的特性來處理:
var obj = {
name: 'qiutc',
foo: function() {
console.log(this);
},
foo2: function() {
console.log(this);
var _this = this;
setTimeout(function() {
console.log(this); // Window
console.log(_this); // Object {name: "qiutc"}
}, 1000);
}
}
obj.foo2();
可以看到直接用 this 仍然是 Window;因為 foo2 中的 this 是指向 obj,我們可以先用一個變量 _this 來儲存,然后在回調函數中使用 _this,就可以指向當前的這個對象了;
setTimeout 的另一個坑
之前啊說過,如果直接執行回調函數而沒有綁定作用域,那么它的 this 是指向全局對象(window),在嚴格模式下會指向 undefined,然而在 setTimeout 中的回調函數在嚴格模式下卻表現出不同:
'use strict';
function foo() {
console.log(this);
}
setTimeout(foo, 1);
// window
按理說我們加了嚴格模式,foo 調用也沒有指定 this,應該是出來 undefined,但是這里仍然出現了全局對象,難道是嚴格模式失效了嗎?
并不,即使在嚴格模式下,setTimeout 方法在調用傳入函數的時候,如果這個函數沒有指定了的 this,那么它會做一個隱式的操作—-自動地注入全局上下文,等同于調用 foo.apply(window) 而非 foo();
當然,如果我們在傳入函數的時候已經指定 this,那么就不會被注入全局對象,比如: setTimeout(foo.bind(obj), 1);;
作為一個構造函數使用
在 js 中,為了實現類,我們需要定義一些構造函數,在調用一個構造函數的時候需要加上 new 這個關鍵字:
function Person(name) {
this.name = name;
console.log(this);
}
var p = new Person('qiutc');
// Person {name: "qiutc"}
我們可以看到當作構造函數調用時,this 指向了這個構造函數調用時候實例化出來的對象;
當然,構造函數其實也是一個函數,如果我們把它當作一個普通函數執行,這個 this 仍然執行全局:
function Person(name) {
this.name = name;
console.log(this);
}
var p = Person('qiutc');
// Window
其區別在于,如何調用函數(new)。
箭頭函數
在 ES6 的新規范中,加入了箭頭函數,它和普通函數最不一樣的一點就是 this 的指向了,還記得在上文中(作為對象的方法調用-一些坑-解決)我們使用閉包來解決 this 的指向問題嗎,如果用上了箭頭函數就可以更完美的解決了:
var obj = {
name: 'qiutc',
foo: function() {
console.log(this);
},
foo2: function() {
console.log(this);
setTimeout(() => {
console.log(this); // Object {name: "qiutc"}
}, 1000);
}
}
obj.foo2();
可以看到,在 setTimeout 執行的函數中,本應該打印出在 Window,但是在這里 this 卻指向了 obj,原因就在于,給 setTimeout 傳入的函數(參數)是一個箭頭函數:
函數體內的this對象,就是定義時所在的對象,而不是使用時所在的對象。
根據例子我們理解一下這句話:
在 obj.foo2() 執行的時候,當前的 this 指向 obj;在執行 setTimeout 時候,我們先是定義了一個匿名的箭頭函數,關鍵點就在這,箭頭函數內的 this 執行定義時所在的對象,就是指向定義這個箭頭函數時作用域內的 this,也就是 obj.foo2 中的 this,即 obj;所以在執行箭頭函數的時候,它的 this -> obj.foo2 中的 this -> obj;
簡單來說, 箭頭函數中的 this 只和定義它時候的作用域的 this 有關,而與在哪里以及如何調用它無關,同時它的 this 指向是不可改變的。
call, apply, bind
在 js 中,函數也是對象,同樣也有一些方法,這里我們介紹三個方法,他們可以更改函數中的 this 指向:
-
call
fun.call(thisArg[, arg1[, arg2[, ...]]])
它會立即執行函數,第一個參數是指定執行函數中 this 的上下文,后面的參數是執行函數需要傳入的參數;
-
apply
fun.apply(thisArg[, [arg1, arg2, ...]])
它會立即執行函數,第一個參數是指定執行函數中 this 的上下文,第二個參數是一個數組,是傳給執行函數的參數(與 call 的區別);
-
bind
var foo = fun.bind(thisArg[, arg1[, arg2[, ...]]]);
它不會執行函數,而是返回一個新的函數,這個新的函數被指定了 this 的上下文,后面的參數是執行函數需要傳入的參數;
這三個函數其實大同小異,總的目的就是去指定一個函數的上下文(this),我們以 call 函數為例;
為一個普通函數指定 this
var obj = {
name: 'qiutc'
};
function foo() {
console.log(this);
}
foo.call(obj);
// Object {name: "qiutc"}
可以看到,在執行 foo.call(obj) 的時候,函數內的 this 指向了 obj 這個對象,成功;
為對象中的方法指定一個 this
var obj = {
name: 'qiutc',
foo: function () {
console.log(this);
}
}
var obj2 = {
name: 'tcqiu222222'
};
obj.foo.call(obj2);
// Object {name: "tcqiu222222"}
可以看到,執行函數的時候這里的 this 指向了 obj2,成功;
為構造函數指定 this
function Person(name) {
this.name = name;
console.log(this);
}
var obj = {
name: 'qiutc2222222'
};
var p = new Person.call(obj, 'qiutc');
// Uncaught TypeError: Person.call is not a constructor(…)
這里報了個錯,原因是我們去 new 了 Person.call 函數,而非 Person ,這里的函數不是一個構造函數;
換成 bind 試試:
function Person(name) {
this.name = name;
console.log(this);
}
var obj = {
name: 'qiutc2222222'
};
var Person2 = Person.bind(obj);
var p = new Person2('qiutc');
// Person {name: "qiutc"}
console.log(obj);
// Object {name: "qiutc2222222"}
打印出來的是 Person 實例化出來的對象,而和 obj 沒有關系,而 obj 也沒有發生變化,說明,我們給 Person 指定 this 上下文并沒有生效;
因此可以得出: 使用 bind 給一個構造函數指定 this,在 new 這個構造函數的時候,bind 函數所指定的 this 并不會生效;
當然 bind 不僅可以指定 this ,還能傳入參數,我們來試試這個操作:
function Person(name) {
this.name = name;
console.log(this);
}
var obj = {
name: 'qiutc2222222'
};
var Person2 = Person.bind(obj, 'qiutc111111');
var p = new Person2('qiutc');
// Person {name: "qiutc111111"}
可以看到,雖然指定 this 不起作用,但是傳入參數還是起作用了;
為箭頭函數指定 this
我們來定義一個全局下的箭頭函數,因此這個箭頭函數中的 this 必然會指向全局對象,如果用 call 方法改變 this 呢:
var afoo = (a) => {
console.log(a);
console.log(this);
}
afoo(1);
// 1
// Window
var obj = {
name: 'qiutc'
};
afoo.call(obj, 2);
// 2
// Window
可以看到,這里的 call 指向 this 的操作并沒有成功,所以可以得出: 箭頭函數中的 this 在定義它的時候已經決定了(執行定義它的作用域中的 this),與如何調用以及在哪里調用它無關,包括 (call, apply, bind) 等操作都無法改變它的 this。
只要記住箭頭函數大法好,不變的 this。
Function.prototype.call
-
格式:fx.call( thisArg [,arg1,arg2,… ] );
- call的傳參個數不限,第一個數表示調用函數(fx)函數體內this的指向.從第二個參數開始依次按序傳入函數.
var age = 40;
var xiaoMing = {
age:30
};
var xiaoLi = {
age: 20
};
var getAge = function(){
console.log(this.age);
};
getAge.call( xiaoMing ); //30 表示函數this指向xiaoMing
getAge.call(xiaoLi); //20 表示函數this指向xiaoLi
getAge.call(undefined);//40 getAge.call(undefined)==getAge.call(null)
getAge.call(null);//40
getAge(); //40
如果我們傳入fx.call()的第一個參數數為null,那么表示函數fx體內this指向宿主對象,在瀏覽器是Window對象,這也解釋了getAge.call(undefined);//40。
在此基礎我們可以理解為 getAge()相當于getAge.call(null/undefined),擴展到所有函數,
fx()==fx.call(null) == fx.call(undefined)
值得注意的是嚴格模式下有點區別: this指向null
var getAge = function(){
'use strict'
console.log(this.age);
};
getAge(null);//報錯 age未定義
再來理解this的使用
this的常用場景:
- this位于一個對象的方法內,此時this指向該對象
var name = 'window';
var Student = {
name : 'kobe',
getName: function () {
console.log(this == Student); //true
console.log(this.name); //kobe
}
}
Student.getName();
var name = 'window';
var Student = {
name : 'kobe',
getName: function () {
var name=100;
console.log(this == Student); //true
console.log(this.name); //kobe
}
}
Student.getName(); //getName取得是Student 的name
- this位于一個普通的函數內,表示this指向全局對象,(瀏覽器是window)
var name = 'window';
var getName = function () {
var name = 'kobe'; //迷惑性而已
return this.name;
}
console.log( getName() ); //window
- this使用在構造函數(構造器)里面,表示this指向的是那個返回的對象.
var name = 'window';
//構造器
var Student = function () {
this.name = 'student';
}
var s1 = new Student();
console.log(s1.name); //student
注意: 如果構造器返回的也是一個Object的對象(其他類型this指向不變遵循之前那個規律),這時候this指的是返回的這個Objec.
var name = 'window';
//構造器
var Student = function () {
this.name = 'student';
return {
name: 'boyStudent'
}
}
var s1 = new Student();
console.log(s1.name); //boyStudent
- this指向失效問題
var name = 'window';
var Student = {
name : 'kobe',
getName: function () {
console.log(this.name);
}
}
Student.getName(); // kobe
var s1 = Student.getName;
s1(); //window
原因: 此時s1是一個函數
function () {
console.log(this.name);
}
對一個基本的函數,前面提過this在基本函數中指的是window.
- 在開發中我們經常使用的this緩存法 ,緩存當前作用域下this到另外一個環境域下使用
最后理解apply的用法 Function.prototype.apply
格式: fx.apply(thisArg [,argArray] ); // 參數數組,argArray
- apply與call的作用是一樣的,只是傳參方式不同,
- apply接受兩個參數,第一個也是fx函數體內this的指向,用法與call第一個參數一致.第二個參數是數組或者類數組,apply就是把這個數組元素傳入函數fx.
var add = function (a ,b ,c) {
console.log(a +b +c);
}
add.apply(null , [1,2,3]); // 6
再吃透這個題目就ok
var a=10;
var foo={
a:20,
bar:function(){
var a=30;
return this.a;
}
}
foo.bar()
//20
(foo.bar)()
//20
(foo.bar=foo.bar)()
//10
(foo.bar,foo.bar)()
//10
上題注解:
時刻牢記:作用域鏈查找遵循"就近原則";
this誰調用就指向誰。
var a=10;
var foo={
a:20,
bar:function(){
var a=30; //this 指向 foo :console.log( this == foo) //true
return this.a;
}
}
foo.bar()
//20
// foo.bar() // foo調用,this指向foo , 此時的 this 指的是foo,所以是20
(foo.bar)()
//20
//第一步:
(function(){
var a=30;
return this.a;
})() //作用域鏈向上查找,this 指向外一層的對象foo
(foo.bar=foo.bar)()
//10
foo.bar=foo.bar,【睜大眼睛,是單等號賦值】就是普通的復制,一個匿名函數賦值給一個全局變量,你可以把右邊的foo.bar換成b,
即(b = foo.bar)(),博客里面【this指向失效問題】說過普通的函數里面的this指向window,自然this.a == 10
(foo.bar,foo.bar)() //逗號表達式
//10
//(foo.bar,foo.bar)是一個小括號表達式,小括號表達式會依次創建兩個匿名函數,并返回最后一個的匿名函數值,
(foo.bar,foo.bar) 得到的是這個函數
function(){
var a=30;
console.log( this == foo); //如果不是很了解this的指向就加這個代碼進行檢測
return this.a;
}
,這個是匿名函數,匿名函數的this指的是widnow,那么this.a = 10
來自:http://www.cnblogs.com/libin-1/p/6111454.html