当前位置:网站首页>[Nodejs]Nodejs基础补充(三)-this上下文对象
[Nodejs]Nodejs基础补充(三)-this上下文对象
2022-04-21 08:07:00 【車鈊】
上下文对象this
含义
在Nodejs当中,上下文对象指的就是this指针,指的是用于调用当前可执行代码的引用,也就是被调用的函数所在的环境。【对于上下文这一概念的理解,我认为可以类比叙事类文章,在一段上下关联内的内容当中,this指向的主语大概率是固定的】
this的作用
在一个上下文环境调用他的对象本身(比如,在对象内部这个上下文环境,this指的是它对象本身);
Js的函数都是依赖某个上层对象进行调用的。函数作为对象的方法调用时,this总是指向调用它的对象;
示例
使用样例对不同情况下的this变量进行模拟输出,
情况1:一般情况下(一般函数和类的外部),this指的使全局变量module.exports,
console.log(module.exports === this)
// 输出:true
情况2:在函数内部,this指向的使该函数内的全局变量global
var a = function () {
console.log(module.exports === this)
console.log(this)
}
a()
// 输出:
// flase
// <ref *1> Object [global]
在函数内部对this指针进行操作做,可以看到是等效于对global进行操作的,且该变量全局共享,在对其中的变量二次赋值时会发生覆盖。
var a = function () {
this.name = 123;
console.log(module.exports === this)
// console.log(this)
}
var b = function () {
this.age = 2333;
}
var c = function () {
this.age =3332;
}
a()
b()
c()
console.log(global.name)
console.log(global.age)
// 输出:
// false
// 123
// 3332
情况3:在构造函数内部,this指的是该该对象本身。
针对一个函数,
var ttt = function () {
this.name = 123;
console.log(this)
}
将其作为一个普通函数执行时,this引用指向的时当前的global变量,
// 输出
// <ref *1> Object [global]
将其作为构造函数使用时,指针指向对象本身,
new ttt();
// 输出
// ttt { name: 123 }
版权声明
本文为[車鈊]所创,转载请带上原文链接,感谢
https://blog.csdn.net/DARKNOTES/article/details/124291545
边栏推荐
猜你喜欢
随机推荐
Dapr | 云原生的抽象与实现
线性回归api
【Pytorch】Tensor.contiguous()使用与理解
Class loading and class loader overview
Webapi (VI) - BOM
Comprehensive case: pinyougou project (pinyougou project process, SEO optimization, TDK three labels and codes) will be gradually optimized in the later stage
Postgresql limit sql性能分析
go解析命令行参数 flag包
Ronglian Qimo helps well-known new retail brands and reshapes new links for enterprise growth
About deep learning drawing
Select tab selected dynamic query of selected status
华硕好屏120Hz高刷新率,开启OLED市场全新格局
Eval() function
31省份及直辖市自治区的下拉框代码
MES and ERP need to be integrated to play a key role
在链表结点前插入新结点
逻辑回归----案例:癌症分类预测
xilinx MPSOC EMIO IIC搭建
How did you spend your day in Shenzhen?
PbIdea 如何导入医保大文件








