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,是由函數調用的時候來肯定其指向的函數

相關文章
相關標籤/搜索