天天看点

【面试题】说说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指向的方法

函数是对象,有属于自己的属性和方法。

继续阅读