[英]Using 'this' in object method in node module.exports
Here is my module: 这是我的模块:
module.exports = {
name: '',
email: '',
id: '',
provider: '',
logged_in: false,
isLoggedIn: function(req, res, next){
console.log(this);
}
};
I import it like so: 我这样导入:
var user = require('user');
When I use the isLoggedIn
function as middle with Express, the console logs the global Node object. 当我将
isLoggedIn
函数与Express一起使用时,控制台将记录全局Node对象。 How do I get it to log the object the function is within? 如何获取记录功能所在的对象的信息?
EDIT 编辑
So I have my user object as defined above. 所以我有我上面定义的用户对象。 Depending on various factors this object is populated elsewhere in the program.
根据各种因素,此对象将填充到程序的其他位置。 I with to create a middleware function for express to quickly test of the user is logged in. The obvious place to put this function seemed to be in the user object, but I need access to the logged_in property to evaluate it properly.
我用来创建一个中间件函数来表示要快速测试用户的登录状态。放置此函数的明显位置似乎在用户对象中,但是我需要访问logging_in属性以对其进行正确评估。 Hence use of this.logged_in.
因此使用this.logged_in。
You should put that with IIFE: 您应该使用IIFE:
module.exports = (function() {
return {
name: '',
email: '',
id: '',
provider: '',
logged_in: false,
isLoggedIn: function(req, res, next){
console.log(this);
}
}
})();
You could read about here: http://designpepper.com/blog/drips/an-introduction-to-iifes-immediately-invoked-function-expressions 您可以在此处阅读有关内容: http : //designpepper.com/blog/drips/an-introduction-to-iifes-immediately-invoked-function-expressions
When you pass that as a middle function, I believe you are doing something like ths 当您将其作为中间函数传递时,我相信您正在做类似
func(.., user.isLoggedIn, ..)
When you are doing like this, you are actually detaching isLoggedIn
from the user
object. 当您这样做时,实际上是在将
isLoggedIn
与user
对象分离。 So, by default, if not in strict mode, this
will refer to global object. 因此,在默认情况下,如果不是在严格模式下,
this
将涉及到全局对象。 To fix this, you should bind
the function, like this 要解决这个问题,您应该像这样
bind
函数
func(.., user.isLoggedIn.bind(user), ..)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.