珠峰培训

javascript中this的用法

作者:tx

2016-09-10 22:02:50

328

绑定事件函数中的this

当事件触发时候执行绑定函数中的this就是触发事件的那个主体

document.body.onclick
        = function (){
console.log(this); //这个this => body
}

函数被调用中的this

函数被调用执行时函数中的this要看是谁来调用这个函数。也就是看执行时刻”.”前面是谁。如果没有那么就是window(非严格模式)

function fn(){
console.log(this);
}
fn(); // this => window
var obj = { fn : fn };
obj.fn(); // this => obj

自运行函数中的this

自运行函数中的this是window(非严格模式)

(function (){
console.log(this); //window
})()
var obj = {
fn : (function (){
console.log(this); //window
})()
}

定时器中的this

定时器第一个参数函数执行的时候函数中的this是window,即使是obj.fn也是window

function fn(){
console.log(this);
}
var obj.fn = fn;
window.setTimeout(obj.fn,1000); // window

构造函数中的this是当前实例

构造函数中的this在new实例执行的过程中指向当前的这个实例

function A(){
this.a = 100; //实例
this.b = 200;
}
var a1 = new A(); //this => a1
var a2 = new A(); //this => a2

回调函数中的this

回调函数中的this一般是window

[].sort(function (a,b){
console.log(this); //window
return a - b;
});

call和apply可以强制改变this指向

function fn(){
console.log(this);
}
var obj = {};
fn.call(obj); // this => obj 如果不使用call应该是window

事件中的this和函数调用时候中的this是比较常用的,但是所有的this遇到call和apply就不再遵循规则,以改变后的为准