JavaScript中的this
以下內(nèi)容屬于個(gè)人的歸納總結(jié)(請(qǐng)大神們多多指點(diǎn)!L酢W嵴稀)
隨著函數(shù)的使用場(chǎng)合不同啤月,this
的值會(huì)發(fā)生變化(this代表函數(shù)運(yùn)行時(shí)自動(dòng)生成的一個(gè)內(nèi)部對(duì)象)
全局執(zhí)行
console.log(this);//瀏覽器:Window //node:{}
函數(shù)中執(zhí)行
純粹的函數(shù)調(diào)用
function hello(){
console.log(this);
}
hello();//Window global
可以看到函數(shù)直接調(diào)用時(shí),屬于全局調(diào)用嫉髓,this指全局對(duì)象
嚴(yán)格模式
'use strict';
function hello(){
console.log(this);
}
hello();//undefined
可以看到在嚴(yán)格模式下執(zhí)行純粹的函數(shù)調(diào)用观腊,this指向的是undefined
作為對(duì)象的方法調(diào)用
當(dāng)一個(gè)函數(shù)被當(dāng)作對(duì)象的方法調(diào)用時(shí),this指當(dāng)前這個(gè)對(duì)象
var o = {
x: 7,
test: function(){
console.log(this.x);
}};
o.test(); //this指o這個(gè)對(duì)象
在setTimeout中使用
var o = {
name: 'Jony',
f1: function(){
console.log(this); //全局對(duì)象
},
f2: function(){
console.log(this); //o這個(gè)對(duì)象
setTimeout(this.f1, 1000);
}
};
o.f2();
在setTimeout這里要注意的是:**把this.f1當(dāng)作參數(shù)傳進(jìn)來,這里的參數(shù)指向的是this.f1的引用算行,只是被當(dāng)作普通函數(shù)的直接調(diào)用梧油,所以這里的this跟o沒有關(guān)系,指全局對(duì)象州邢。
**大家可以思考下面這個(gè)例子的打印結(jié)果是什么儡陨??量淌?
'use strict';
function test() {
console.log(this);
}
setTimeout(test, 1000);
上面我提到了在嚴(yán)格模式下this是undefined,但是在setTimeout中this如果沒有指定骗村,相當(dāng)于test.apply(global)
;
作為構(gòu)造函數(shù)調(diào)用
var x = 9;
function test() {
this.x = 8; //this指的構(gòu)造函數(shù)調(diào)用時(shí)實(shí)例化出來的對(duì)象
}
var a = new test();
console.log(a.x); //8
console.log(x); //9
箭頭函數(shù)
在這里我想說一下箭頭函數(shù)的好處之一 :可以改變this的指向請(qǐng)看下面兩段代碼:
var o = {
name: 'Jony',
f1: function(){
console.log(this);
},
f2: function(){
console.log(this); //o這個(gè)對(duì)象
var _this = this;
setTimeout(function(){
console.log(this); //全局對(duì)象
console.log(_this); //o這個(gè)對(duì)象
}, 1000);
}
};
o.f2();
問題:setTimeout中的this是全局對(duì)象因此我們采用閉包的特性——把this存儲(chǔ)在內(nèi)存中,使用這種方式解決上面的問題但是在箭頭函數(shù)中我們可以更方便的解決this的指向問題,請(qǐng)看下面:
var o = {
name: 'Jony',
f1: function(){
console.log(this);
},
f2: function(){
console.log(this); //o這個(gè)對(duì)象
setTimeout(() => {
console.log(this); //o這個(gè)對(duì)象
}, 1000);
}
};
o.f2();//箭頭函數(shù)中的this只跟定義它時(shí)作用域中的this有關(guān)
以上是我對(duì)JS中的this淺顯的理解呀枢,僅供參考胚股!