1. 普通函數(shù) this 指向window
function fn() {
console.log('普通函數(shù)的this' + this);
}
window.fn();

image.png
2. 對(duì)象的方法 this指向的是"這個(gè)對(duì)象"
var o = {
sayHi: function() {
console.log('對(duì)象方法的this:' + this);
}
}
o.sayHi();

image.png
3.構(gòu)造函數(shù) this 指向 ldh 這個(gè)實(shí)例對(duì)象 原型對(duì)象里面的this 指向的也是 ldh這個(gè)實(shí)例對(duì)象
function Star(name,age) {
this.name = name
this.age = age
console.log(this)
};
Star.prototype.sing = function() {
console.log(this.name + '在唱歌')
}
var ldh = new Star("張三",22);
console.log(ldh)
ldh.sing()

image.png
4. 綁定事件函數(shù) this 指向的是函數(shù)的調(diào)用者 btn這個(gè)按鈕對(duì)象
var btn = document.querySelector('button');
btn.onclick = function() {
console.log('綁定時(shí)間函數(shù)的this:' + this);
};

image.png
5.定時(shí)器函數(shù) this 指向的是window
window.setTimeout(function() {
console.log('定時(shí)器的this:' + this);
}, 1000);

image.png
6. 立即執(zhí)行函數(shù) this指向window

image.png
改變this指向的方法
js提供了三種方法 call() apply() bind()
1.call
- call 第一個(gè)可以調(diào)用函數(shù) 第二個(gè)可以改變函數(shù)內(nèi)的this 指向
var obj = {
name: 'andy'
}
function fn(a, b) {
console.log(this);
console.log(a + b);
};
fn.call(obj, 11, 230)
- call 的主要作用可以實(shí)現(xiàn)繼承(call方法的第二個(gè)作用)
function Father(uname, age, sex) {
this.uname = uname;
this.age = age;
this.sex = sex;
}
function Son(uname, age, sex) {
Father.call(this, uname, age, sex);
}
var son = new Son('劉德華', 18, '男');
console.log(son);

image.png
2.apply
- 調(diào)用函數(shù) 第二個(gè)可以改變函數(shù)內(nèi)部的this指向
- 但是他的參數(shù)必須是數(shù)組(偽數(shù)組)
var o = {
name: 'andy'
}
function fn(a, b) {
console.log(this);
console.log(a + b);
};
fn.apply(o, [1, 2])

image.png
3.bind
- 不會(huì)調(diào)用原來(lái)的函數(shù) 可以改變?cè)瓉?lái)函數(shù)內(nèi)部的this 指向
- 返回的是原函數(shù)改變this之后產(chǎn)生的新函數(shù)
應(yīng)用場(chǎng)景:
有函數(shù)但不需要立即調(diào)用時(shí),但是又想改變這個(gè)函數(shù)內(nèi)部的this指向此時(shí)用bind
var o = {
name: 'andy'
};
function fn(a, b) {
console.log(this);
console.log(a + b);
};
var f = fn.bind(o, 1, 2);
f();
- 應(yīng)用場(chǎng)景舉例
<button>點(diǎn)擊</button>
<button>點(diǎn)擊</button>
<button>點(diǎn)擊</button>
var btns = document.querySelectorAll('button');
console.log(btns)
for (var i = 0; i < btns.length; i++) {
btns[i].onclick = function() {
this.disabled = true;
setTimeout(function() {
console.log(this)
this.disabled = false;
}, 2000);
}
}
call,apply,bind區(qū)別
call,apply,bind主要作用都是改變this指向的,但使用上略有區(qū)別,說(shuō)一下區(qū)別:
call和apply的主要區(qū)別是在傳遞參數(shù)上不同,call后面?zhèn)鬟f的參數(shù)是以逗號(hào)的形式分開(kāi)的,apply傳遞的參數(shù)是數(shù)組形式 [Apply是以A開(kāi)頭的,所以應(yīng)該是跟Array(數(shù)組)形式的參數(shù)]
bind返回的是一個(gè)函數(shù)形式,如果要執(zhí)行,則后面要再加一個(gè)小括號(hào) 例如:bind(obj,參數(shù)1,參數(shù)2,)(),bind只能以逗號(hào)分隔形式,不能是數(shù)組形式