有关this的指向问题

    科技2022-07-16  100

    this指向问题

    this指向问题 this 一般情况下this指向的是那个调用它的对象

    全局作用域或者普通函数中this指向全局对象window (注意定时器里面的this指向window) // 1. 全局作用域或者普通函数中this指向全局对象window (注意定时器里面的this指向window) console.log(this); //指向window function fn() { console.log(this); } window.fn(); //其实是省略了这个 指向window window.setTimeout(function () { console.log(this); }, 1000); //指向window 方法调用中的this指向调用的方法 // 2.方法调用中的this指向调用的方法 var o = { sayHi: function () { console.log(this); //this 指向的是 o 这个对象 }, }; o.sayHi(); var btn = document.querySelector("button"); btn.addEventListener("click", function () { console.log(this); //this 指向的是 btn 这个对象 }); 构造函数里面的this指向构造函数的实例 // 3.构造函数里面的this指向构造函数的实例 function Fun() { console.log(this); //this 指向的是fun 实例对象 } var fun = new fun();
    Processed: 0.010, SQL: 8