- 普通模式調(diào)用函數(shù)片吊,函數(shù)中的this是window渗稍。
function a(){
var user = "b";
console.log(this); //Window
}
a();
- 如果是通過new的方式,函數(shù)中的this就是當(dāng)前的實(shí)例對象。
function Fn(){
this.user = "張三";
}
var a = new Fn();
console.log(a.user); //張三
- 對象中的方法曹质,里面的this還是當(dāng)前實(shí)例對象。
var o = {
user: "李四",
fn: function () {
console.log(this.user);//李四
}
}
o.fn();
- 全局函數(shù)apply和call可以用來改變this的指向
var fun = function(str) {
this.status = str;
}
fun.prototype.getStatus = function() {
alert(this.status);
}
var obj = {
status: "loading"
};
fun.prototype.getStatus.apply(obj); // 輸出"loading", 此時(shí)getStatus方法中的this指向了obj
補(bǔ)充一點(diǎn):在嚴(yán)格模式(use strict;
)中的默認(rèn)的this不再是window擎场,而是undefined羽德。