聊聊JS中的this

150 阅读1分钟

this的定义

我们在js中主要研究的是函数中的this,this代表当前行为执行的主体,JS中的context是当前行为执行的环境,即执行区域。非函数中的this指的是window,没有研究必要。

区分this

this主要出现在函数内部使用/对象方法调用/new/箭头函数/call、apply、bind等,这些我们不谈,博客有很多,我们从另一角度区分this指向问题。
(1)函数执行时,函数名前是否有“.”,前面是谁,this就是谁;否则就是window

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

function sum() {
    fn();  //this->window
}
sum();  //sum中this-> window

var oo = {
    sum: function () {
        fn(); //this-> window
    }
};
oo.sum(); // sum中this->oo

(2)自执行函数中的this永远指向window;
(3)给元素某个事件绑定方法,当事件触发时,执行对应方法 方法中this是当前元素;

document.getElementById("div1").onclick = fn; //fn中this是#div1  
document.getElementById("div1").onclick = function () {  
    //this-> #div1
    fn(); //this-> window
};