this 指向问题
基本环境
function
function构造函数
箭头函数
call,apply,bind
function
原则:this永远指向运行时调用这个方法的对象
代码块
function fun(){
const text = ‘test’;
console.log(this.text); // undefined
console.log(this); // Window
}
fun();
window.fun(); // 这样写等价于
// 调用者是window,所以this指向window
代码块
function obj = {
text: ‘test’,
fun: function(){
console.log(this.text); // test
}
}
obj.fun();
// this指向这个函数的调用者,调用者是obj,那this就是obj
代码块
function obj = {
a: 10,
b: {
a: 12,
fun: function(){
console.log(this.a); // 12
}
}
}
obj.b.fun();
// 调用fun的是obj中的b,所以this指向obj中的b
代码块
function obj = {
a: 10,
b: {
a: 12,
fun: function(){
console.log(this.a); // undefined
console.log(this); // window
}
}
}
const j = obj.b.fun;
j();
// 把fun这个函数赋值给了j,再执行j的时候,调用者就变成了window,所以this是window
function构造函数
new 关键字会改变this指针的指向
代码块
JavaScriptfunction obj() {
this.x = ‘x’;
this.fun = function() {
console.log(this.x);// x
}
}
const o = new obj();
o.fun();
// new关键字将this指向了o,不太恰当的理解是o就是这个obj方法是等价的,里面的fun方法用function关键字定义的,用这个关键字定义的方法,里面用到的this会指向调用者,就是o,o里面有x这个属性,所以可以正常输出
箭头函数
原则:this 指向在定义时指定,非运行时指定。this指向的是其上一层作用域的this,另外对象不能形成独立作业域。
call apply bind
通过这三个方法都可以改变this的指向,区别是call和apply会立即执行,bind不会,call和apply的区别是后续接受的参数不同,call是连续参数,apply是数组。
代码块
JavaScriptconst obj = {
a: 10,
b: {
a: 12,
fun: function(){
console.log(this.a);
}
}
}
const j = obj.b.fun;
j();// undefined
j.call(obj);// 10
j.call(obj.b);// 12
//把this变成传入的对象
代码块
var obj = {
a: 10,
b: {
a: 12,
fun: function(){
console.log(this.a);
}
}
}
const j = obj.b.fun;
j();// undefined
j.apply(obj);// 10
j.apply(obj.b);// 12
//把this变成传入的对象
代码块
const obj = {
a: 10,
b: {
a: 12,
fun: function(){
console.log(this.a);
}
}
}
const j = obj.b.fun;
j();// undefined
let c = j.bind(obj);
c();// 10
c = j.bind(obj.b);
c();// 12
//把this变成传入的对象,但是不会立马执行,而是返回一个新的对象,想执行得去执行新的对象