JavaScript this指向
-
全局环境下:
this 始终指向全局对象(window), 无论是否严格模式
console.log(this.document === document); // true // 在浏览器中,全局对象为 window 对象: console.log(this === window); // true this.a = 37; console.log(window.a); // 37
-
普通函数调用:
非严格模式下:指向全局对象 :window; 严格模式:this是undefined
function f1(){ return this; // 非严格模式:普通函数的this指向window } f1() === window; // true
function f1(){ "use strict"; // 这里是严格模式 return this; // 严格模式:普通函数的this是undefined } f1() === window; // false
// let 声明的变量 let username = 'username' function fn(){ alert(this.username); // undefined let声明的变量不在window上 } fn();
// var 声明的变量 var username = 'username' function fn(){ alert(this.username); // username } fu();
// 直接挂载在 window 上的变量 window.username = 'username' function fn(){ alert(this.username); // username } fn(); //可以理解为 window.fn();
-
对象函数调用:
哪个对象函数调用,this就指向哪里
window.b=2222 let obj={ a:111, fn:function(){ alert(this.a);//111 alert(this