JavaScript中函数的调用和this的指向

欢迎纠正和补充c++

函数的调用和this的指向

1.普通函数调用 this 指向 window

function fn() {
    console.log(this);
}
window.fn();

2.方法调用 this 指向 调用该方法的对象

var obj = {
    fun: function () {
        console.log(this);
    }
}
obj.fun();

3.做为构造函数的调用 构造函数内部的this指向由该构造函数建立的对象

var gf = {
    name : "tangwei",
    bar : "c++",
    sayWhat : function() {
        console.log(this.name + "said:love you forever");
    }
}

4.做为事件的处理函数 触发该事件的对象

btn.onclick = function () {
    console.log(this);
}

5.做为定时器的参数 this 指向 window

setInterval(function() {
    console.log(this);
}, 1000);

总结:函数内部的this,是由函数调用的时候来肯定其指向的函数

相关文章
相关标签/搜索