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的对象,)
[*]bind:不立刻调用,而是返回一个新函数,this 被永世绑定。通报给函数的参数格式是:(盼望绑定给this的对象,arg1,arg2,……)
隐式绑定
普通函数调用
在严格模式中
function fun(){
//设置在严格模式下
"use strict";
//打印:undefined
console.log(this)
}
fun() 在浏览器环境中
https://i-blog.csdnimg.cn/direct/8d06d5c77d7c4a57b14d1ef0afe1f45b.png
在Node.js环境中
function fun(){
//打印:global对象
console.log(this)
}
//在Node.js环境中调用这个函数,且这个函数没有显式指定 this,那么this默认指向global对象。
fun() https://i-blog.csdnimg.cn/direct/683890c5d26f4e2fa2fbf4a9237ae52c.png
对象的方法调用
const student = {
name: "张三",
sex: "男",
selfIntroduction() {
//这里的this就是student对象
console.log("姓名:",this.name,";性别:",this.sex)
}
}
student.selfIntroduction()
//等价于
console.log("姓名:",student.name,";性别:",student.sex) https://i-blog.csdnimg.cn/direct/9459f15a2ec641f3a30b1e77817b2476.png
构造函数调用
function Student(name,sex){
this.name=name
this.sex=sex
//打印Student对象的信息
console.log(this)
}
new Student("张三","男") https://i-blog.csdnimg.cn/direct/af610ebe74904b10abecdd0b0bbb3607.png
setTimeout回调的环境
const obj = {
sayLater: function () {
setTimeout(function () {
//在Node.js环境下,this绑定成了这个Timeout实例。而非obj对象。
//在浏览器中运行则是window对象。
console.log(this)
}, 1000);
}
};
obj.sayLater(); https://i-blog.csdnimg.cn/direct/27b63a9a34254d51bee2c605bc8b734e.png
https://i-blog.csdnimg.cn/direct/c6f84c9da33942d3ac78990a816190c9.png
在箭头函数中
注意:普通函数和箭头函数最大的区别就是,普通函数中的this指向调用方,而箭头函数中的this继续外层的上下文。我们刚才演示了this在setTimeout回调的环境,按照刚才的理论,如果使用箭头函数this应该指向sayLater对象。看下面的案例:
const obj = {
sayLater: function () {
setTimeout( ()=> {
console.log(this)
}, 1000);
}
};
obj.sayLater(); https://i-blog.csdnimg.cn/direct/662a35b31ae14e708b30b720229f9302.png
显式绑定
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()
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页:
[1]