nodejs中this详解

最近在用Nodejs进行APP运维服务管理系统开发时发现,nodejs中的this经常会变,查了下资料后发现this在不同的代码位置中代表不同的涵义,在实际运用过程中可以用var self = this接住函数外的this,在函数内用self.xxx继续使用详情如下,

以下内容都是关于在nodejs中的this而非javascript中的this,nodejs中的this和在浏览器中javascript中的this是不一样的。

在全局中的this

?
1
2
3
4
console.log( this ); {}
this .num = 10;
console.log( this .num); 10
console.log(global.num); undefined

  全局中的this默认是一个空对象。并且在全局中this与global对象没有任何的关系,那么全局中的this究竟指向的是谁?在本章节后半部分我们会讲解。

在函数中的this

?
1
2
3
4
5
6
7
function fn(){
   this .num = 10;
}
fn();
console.log( this ); {}
console.log( this .num); undefined
console.log(global.num); 10

  在函数中this指向的是global对象,和全局中的this不是同一个对象,简单来说,你在函数中通过this定义的变量就是相当于给global添加了一个属性,此时与全局中的this已经没有关系了。

如果不相信,看下面这段代码可以证明。

?
1
2
3
4
5
6
7
8
9
10
function fn(){
   function fn2(){
     this .age = 18;
   }
   fn2();
   console.log( this ); global
   console.log( this .age); 18
   console.log(global.age); 18
}
fn();

  对吧,在函数中this指向的是global。

构造函数中的this

?
1
2
3
4
5
6
function Fn(){
   this .num = 998;
}
var fn = new Fn();
console.log(fn.num); 998
console.log(global.num); undefined

  在构造函数中this指向的是它的实例,而不是global。

  我们现在可以聊聊关于全局中的this了,说到全局中的this,其实和Nodejs中的作用域有一些关系,如果你想了解Nodejs中关于作用域的信息可以看探讨Nodejs中的作用域问题。这篇文章。

  回到正题,全局中的this指向的是module.exports。

?
1
2
3
this .num = 10;
console.log(module.exports); {num:10}
console.log(module.exports.num);

转载于:https://www.cnblogs.com/wjcoding/p/11310077.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值