在 JavaScript 中,关键字 this
用于引用当前执行代码的对象。它的值是不固定的,取决于函数的调用方式
this的常见的指向
-
全局上下文中的
this
:在全局作用域中,this
指向全局对象(浏览器环境下指向window
对象,Node.js 环境下指向global
对象) -
函数中的
this
:在函数内部,this
的值取决于函数的调用方式- 作为普通函数调用时,
this
指向全局对象(非严格模式下)或undefined
(严格模式下) - 作为对象方法调用时,
this
指向调用该方法的对象 - 作为构造函数调用时,
this
指向新创建的实例对象
- 作为普通函数调用时,
- 使用
call
、apply
或bind
方法显式指定时,this
指向指定的对象 - 箭头函数中的
this
指向定义时所在的作用域,而不是调用时的对象 -
事件处理函数中的
this
:在事件处理函数中,this
指向触发该事件的元素// 全局上下文中的 this console.log(this); // 浏览器环境下:Window,Node.js 环境下:global // 函数中的 this function sayHello() { console.log(this); } sayHello(); // 浏览器环境下:Window,Node.js 环境下:undefined var person = { name: "John", sayName: function() { console.log(this.name); } }; person.sayName(); // John // 构造函数中的 this function Person(name) { this.name = name; } var john = new Person("John"); console.log(john.name); // John // call、apply 或 bind 方法中的 this var person2 = { name: "John" }; function sayName(message) { console.log(message + this.name); } sayName.call(person2, "Hello, "); // Hello, John // 箭头函数中的 this var obj = { func: function() { setTimeout(() => { console.log(this); }, 1000); } }; obj.func(); // obj 对象
注意:箭头函数没有自己的this,它的this取决于所在外部作用域的this,它会继承外部作用域的this