IT评测·应用市场-qidao123.com技术社区
标题:
JavaScript中的this到底是什么
[打印本页]
作者:
自由的羽毛
时间:
2025-4-26 07:13
标题:
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";
//打印:undefined
console.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=name
this.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()
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
欢迎光临 IT评测·应用市场-qidao123.com技术社区 (https://dis.qidao123.com/)
Powered by Discuz! X3.4