天天看點

【面試題】說說JS中的this指向問題

JS中的this指向問題

this的指向問題

全局作用域

在JS中,全局的變量和函數附着在​

​global​

​​對象上,全局對象在浏覽器環境下是​

​window​

​對象。

  • 在全局作用域中,​

    ​this​

    ​​指向全局對象​

    ​window​

    ​。
console.log(this);      // window對象
console.log(window);    // window對象
console.log(this === window);    // true      
var a = 3;

console.log(a);                                     // 3
console.log(window.a);                              // 3
console.log(this.a);                                // 3
console.log(a === window.a && window.a === this.a); // true      
function say(){
    console.log("hi");
}

this.say();     // hi      

全局變量和window對象的關系

  • 使用​

    ​var​

    ​聲明定義的全局變量會被挂載到全局對象​

    ​window​

    ​上。
  • 使用​

    ​let​

    ​、​

    ​const​

    ​聲明定義的全局變量不會被挂載到全局對象​

    ​window​

    ​上。

普通函數

普通函數内部的​

​this​

​指向調用這個函數的對象。

案例1

function testThis(){
    console.log(this);
}

testThis();     // 輸出結果: window對象      

​testThis()​

​​在全局作用域中被調用,相當于執行了​

​window.testThis();​

​​,則函數被調用時,内部的​

​this​

​​指向​

​window​

​.

案例2

var obj = {
    test(){
        console.log(this);
    }
}

obj.test();     // obj      
普通函數作為對象上的方法時,​

​this​

​指向調用方法的對象.

案例3

var obj = {
    test1(){
        console.log(this);
    },
    test2(){
        test();    // 這裡相當于執行了window.test();
    }
}

function test(){
    console.log(this);
}

obj.test1();     // obj
obj.test2();     // window
test();          // window      

構造函數

構造函數一般是通過​

​new​

​​關鍵字調用的,其内部的​

​this​

​指向新建立的對象。

function Person(name,age){
    this.name = name;
    this.age = age;
    console.log(this);
}

const person1 = new Person('張三',20);
const person2 = new Person('李四',18);      
構造函數利用指向新對象的​

​this​

​​,将傳入的​

​name​

​​和​

​age​

​​屬性直接指派給新對象。通過最後的​

​console.log(this)​

​​語句也可以檢測出​

​this​

​的指向。

綁定事件函數

const btn = document.querySelector('button');

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

    ​指向觸發該事件的對象。
此處,點選事件觸發時,​

​this​

​​指向按鈕這個​

​DOM​

​對象。

箭頭函數

箭頭函數沒有屬于自己的​

​this​

​​。是以,箭頭函數内部使用的​

​this​

​​就是箭頭函數所在上下文的​

​this​

​.

var obj = {
    test1(){
        console.log(this);
    },
    test2:()=>{
        console.log(this);
    }
}
obj.test1();     // obj
obj.test2();     // window      

​test2​

​​是箭頭函數,沒有屬于自己的​

​this​

​​。在其内部輸出的​

​this​

​​是​

​obj​

​​所在上下文的​

​this​

​​,即​

​window​

​。

改變this指向的方法

函數是對象,有屬于自己的屬性和方法。

繼續閱讀