不同开发法环境下全局环境中this指向
提醒: this 的指向是在代码运行时,被动静绑定的。
- 浏览器中下全局环境的 this 指向 window
//测试console.log(this); // window
- node 中全局环境的 this 指向 global
//测试console.log(this) // global
- "use strict" 严格模式下全局环境的 this 指向 undefined
"use strict"// 测试console.log(this) // undefined
谁调用 this 就指向谁
- 函数在全局环境中自行调用时函数中 this 指向全局环境中 this 指向的对象
留神: 全局环境中的函数自行调用相似于被全局环境中 this 指向的对象所调用(如:window.F())
let name = "Jason"function getName() { console.log(this.name);}1. 浏览器中getName() // Jason, this -> window// 相似于window.getName()3. node 环境中getName() // Jason, this -> global// 相似于global.getName()3. 严格模式中"use strict" getName() // undefined, this -> undefined// 相似于undefined.getName()
- 对象中的办法在被对象调用时 this 指向调用它的对象
let user = { name: "Jason", getName: function(){ console.log(this); console.log(this.name); }, obj: { age: 23, getAge: function(){ console.log(this); console.log(this.age); } }}// 测试user.getName() // user Jason, this -> useruser.obj.getAge() // obj 23, this -> obj
构造函数中的 this 指向构造函数的实例对象
function User(name, age) { this.name = name; this.age = age;}User.prototype.getUser = function(){ console.log(this)}// 测试let user = new User("Jason", 23)user.getUser();// this 指向构造函数实例, this -> user
setTiemout, setInterval 中的 this 指向全局中的 this
let F = ()=> { setTimeout(function(){ console.log(this) },2000)}// 测试F(); // window, this -> window
Class 中的 this 指向类实例的对象
class User { constructor(name, age) { this.name = name; this.age = age; } getUser(){ console.log(this.name); console.log(this.age); console.log(this); }}// 测试let user = new User("Jason", 23);user.getUser() // Jason 23, this -> user
箭头函数中没 this, 如果箭头函数中应用 this 的话, this 指向取决于外层对象或函数的 this 指向
setTimeout(()=>{ console.log(this);},3000)// this -> windeow, 箭头函数中的 this 指向取决于 setTimeout 的 this 指向