this指向问题
码农天地 -不同开发法环境下全局环境中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 -> user
user.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 指向全局中的 thislet 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 指向
特别申明:本文内容来源网络,版权归原作者所有,如有侵权请立即与我们联系(cy198701067573@163.com),我们将及时处理。
上一篇: v-router学习笔记