JavaScript中的this到底是什么
目录
目标
概述
隐式绑定
普通函数调用
在严格模式中
在浏览器环境中
在Node.js环境中
对象的方法调用
构造函数调用
setTimeout回调的情况
在箭头函数中
显式绑定
call
apply
bind
目标
了解this的基本概念,通过案例了解this在不同环境下的指向。
概述
this是什么
this是当前执行上下文中所指向的对象(实际上就是这个对象的指针或引用),它取决于函数是如何被调用的。也就是说,this是执行上下文的属性。
隐式绑定
也叫自动绑定。通过对象调用方法时,this指向这个对象。函数直接调用指向全局对象(实际上是全局对象调用了函数)。当然,在严格模式下是undefined。
显式绑定
调用call,apply或bind明确指定this。显式绑定在回调函数和定时器中经常使用到。它们之间的特点如下:
- call:立即调用函数并显式指定this,传递给函数的参数格式是:(希望绑定给this的对象,arg1,arg2,……)
- apply:立即调用函数并显式指定this,传递给函数的参数格式是:(希望绑定给this的对象,[arg1,arg2,……])
- bind:不立刻调用,而是返回一个新函数,this 被永久绑定。传递给函数的参数格式是:(希望绑定给this的对象,arg1,arg2,……)
隐式绑定
普通函数调用
在严格模式中
function fun(){//设置在严格模式下"use strict";//打印:undefinedconsole.log(this)
}
fun()
在浏览器环境中
在Node.js环境中
function fun(){//打印:global对象console.log(this)
}
//在Node.js环境中调用这个函数,且这个函数没有显式指定 this,那么this默认指向global对象。
fun()
对象的方法调用
const student = {name: "张三",sex: "男",selfIntroduction() {//这里的this就是student对象console.log("姓名:",this.name,";性别:",this.sex)}
}
student.selfIntroduction()
//等价于
console.log("姓名:",student.name,";性别:",student.sex)
构造函数调用
function Student(name,sex){this.name=namethis.sex=sex//打印Student对象的信息console.log(this)
}
new Student("张三","男")
setTimeout回调的情况
const obj = {sayLater: function () {setTimeout(function () {//在Node.js环境下,this绑定成了这个Timeout实例。而非obj对象。//在浏览器中运行则是window对象。console.log(this)}, 1000);}
};
obj.sayLater();
在箭头函数中
注意:普通函数和箭头函数最大的区别就是,普通函数中的this指向调用方,而箭头函数中的this继承外层的上下文。我们刚才演示了this在setTimeout回调的情况,按照刚才的理论,如果使用箭头函数this应该指向sayLater对象。看下面的案例:
const obj = {sayLater: function () {setTimeout( ()=> {console.log(this)}, 1000);}
};
obj.sayLater();
显式绑定
call
function fun(name, sex) {console.log(`name:${name},sex:${sex},age:${this.age}`)
}const student = {name: "张三", sex: "男", age: "18"
}
//打印:name:李四,sex:女,age:18
fun.call(student,"李四","女")
apply
function fun(name, sex) {console.log(`name:${name},sex:${sex},age:${this.age}`)
}const student = {name: "张三", sex: "男", age: "18"
}
//打印:name:李四,sex:女,age:18
fun.apply(student,["李四","女"])
bind
function fun(name, sex) {console.log(`name:${name},sex:${sex},age:${this.age}`)
}const student = {name: "张三", sex: "男", age: "18"
}
const stu=fun.bind(student,"李四","女")
//打印:function
console.log(typeof stu)
//打印:name:李四,sex:女,age:18
stu()