在javascript中的this大致可以理解成誰(shuí)調(diào)用的this就指向誰(shuí)
全局環(huán)境中的this
alert(this);//window
函數(shù)中的this
var name = 'tom';
function say(){
var name = 'bob'
alert(this.name);
}
say();//tom
調(diào)用say()等價(jià)于window.say(),所以this最終指向window
對(duì)象中的this
var name = 'tom';
var obj = {
name: 'bob',
say: function(){
alert(this.name);
}
}
//第一種調(diào)用形式
obj.say();//bob; 對(duì)象直接調(diào)用所以this指向obj
//第二種調(diào)用形式
var tSay = obj.say;
tSay();//tom; 最終tSay還是通過(guò)window調(diào)用偏螺,所以最終this指代window對(duì)象
做為構(gòu)造函數(shù)中的this
function A(){
console.log(this);
}
var a = new A();// function A(){console.log(this)}
函數(shù)中的函數(shù)的this
var name = 'tom';
var obj = {
name: 'bob',
say: function(){
function _say(){
alert(this.name);
}
_say();
}
}
obj.say();//tom 最終調(diào)用_say的是window 所以this指向window
apply肯尺、call可以改變this指向
var obj1 = {
name: 'tom'
}
var obj2 = {
name: 'bob',
say: function(){
alert(this.name);
}
}
obj2.say.call(obj1);//tom 最終this指向obj1
obj2.say.apply(obj1);//tom 最終this指向obj1
通過(guò)apply无蜂、call可以改變this指向
call和apply實(shí)現(xiàn)的功能是相同,區(qū)別在于傳參部分
call( thisArg [, arg1,arg2, … ] ); // 參數(shù)列表粟害,arg1掉房,arg2茧跋,...
apply(thisArg [, argArray] ); // 參數(shù)數(shù)組,argArray
在點(diǎn)擊事件中的this
<div id="button">點(diǎn)擊</div>
var obj = {
name: 'bob',
say: function(){
alert(this.name);
}
}
let oButton = document.getElementById('button');
oButton.onclick = obj.say;//undefined 因?yàn)樽罱K調(diào)用say的是oButton卓囚,oButton沒(méi)有定義name屬性所以最終結(jié)果是undefined
我們可以通過(guò)ES5中引入的bind方法來(lái)解決這個(gè)問(wèn)題
oButton.onclick = obj.say.bind(obj);//強(qiáng)制綁定obj.say的this指向?yàn)閛bj瘾杭,所以最終結(jié)果是bob;
我們可以自己模擬bind方法,比如:
Function.prototype.bind = function(){
var fn = this, args = Array.prototype.slice.call(arguments), object = args.shift();
return function(){
return fn.apply(object,
args.concat(Array.prototype.slice.call(arguments)));
};
};