this 是什么 ?
this是包含它的函數(shù) 作為方法被調(diào)用時 所屬的對象。
function arr(){
console.log(this); //window
}
arr(); //window
this 指向 window 的情況
全局下調(diào)用函數(shù): this指向window
function foo() {
console.log(this); // window
}
foo();
定時器與延時器中的this
setInterval(function () {
console.log(this); // window
});
setTimeout(function () {
console.log(this); // window
});
自執(zhí)行函數(shù)
(function () {
console.log(this); // window
})()
閉包
function arr() {
return function () {
console.log(this); // window
}
}
var boo = arr();
boo(); // 最后是window調(diào)用了這個函數(shù)
改變 this 指向的三種方法
通常情況下,我們想使用其它環(huán)境變相下的狀態(tài),這就需要借助this來實現(xiàn),常用改變this指向的有以下幾種方式可以實現(xiàn)
call()
語法:
函數(shù).call(this, 參數(shù)1, 參數(shù)2, ...)
會立即執(zhí)行該函數(shù)
var arr = {
name: '胖子',
fn(a, b) {
console.log(this.name, a, b); // 瘦子 a b
}
}
var abb = {
name: '瘦子',
}
arr.fn.call(abb, 'a', 'b'); //瘦子 a b
apply()
語法:
函數(shù).apply(this, [參數(shù)1, 參數(shù)2, ...])
會立即執(zhí)行該函數(shù)
var arr = {
name: '胖子',
fn(a, b) {
console.log(this.name, a, b); // 瘦子 a b
}
}
var abb = {
name: '瘦子',
}
arr.fn.apply(abb, 'a', 'b'); //瘦子 a b
bind()
函數(shù).bind(this, 參數(shù)1, 參數(shù)2,...);
不會立即執(zhí)行,返回一個新的函數(shù),函數(shù)體內(nèi)的this指向傳入的對象,參數(shù)以逗號隔開,并且會自動拼接, bind 跟call相似,只不過后面多了個 ()