JavaScript中this指向
1、在全局作用域下this指向window
2、函数中:
情况一、普通函数
foo(); this指向window
obj.foo(); this指向obj
new的方式(构造函数时,new一个对象) this指向new出来的实例
情况二、箭头函数
this指向包裹箭头函数的第一个普通函数
情况三、call、apply、bind
this被强制绑定到指定的对象上
3、在class中,this指向新创建的类实例:
一种写法是构造函数创建
function Boo(a) {
this.a = a;
this.say = function() {
console.log(`say ${this.a}`);
}
}
const boo = new Boo(‘hello’);
另外一种是es6写法,利用class关键字
class Boo {
constructor(a) {
this.a = a;
}
say(){
console.log(`I say ${this.a}`);
}
}
const boo = new Boo(‘hello’);
本文详细介绍了JavaScript中this的关键指向规则,包括全局作用域、函数调用、箭头函数、call/apply/bind方法以及在class中的应用。在全局作用域下,this指向window;在函数中,普通函数调用时this指向window,而作为对象方法时指向调用该方法的对象;箭头函数的this继承自父级作用域;call、apply、bind可以强制改变this指向。在class中,无论哪种构造方式,this都指向新创建的类实例。
2726

被折叠的 条评论
为什么被折叠?



