gpt4 book ai didi

javascript - 在原型(prototype)方法中使用 'this' 时丢失上下文

转载 作者:行者123 更新时间:2023-11-30 05:36:14 24 4
gpt4 key购买 nike

好的,所以我有一个使用 express 的 Node 应用程序。在这个应用程序中,我有一条像这样的快速路线:

var   MyObj = require('./myObj')
, myObj = new MyObj();
app.post('/api/blah', auth.requiresLogin, myObj.method2);

现在在 MyObj 对象中我有以下内容:

var MyObj = function(name){
this.name = name;
this.message = 'hello';

};

MyObj.prototype = {
method1: function(req, res, done){
console.log('In Method 1');
done(null, this.message +' '+this.name);
},
method2: function(req, res){

var message;

console.log('In Method 2');

this.method1(req, res, function(err, value){
if(err) throw err;
message = value;
console.log(this.message);
});

return message;
}
};

module.exports = MyObj;

现在,如果我不需要这个对象并从同一个文件中调用它,它就可以工作。正如这个 jsFiddle 上所演示的:http://jsfiddle.net/britztopher/qCZ2T/ .但是,如果我需要它,用新的构造它,并尝试调用 myObj.method2(req, res);从需要的类(class)中我得到 #<Object> has no method 'method1' .不知道我在这里做错了什么,或者它的 expressJS 或 require JS 给我带来了问题。另外,当我看里面时 this在 method2 中是 this = global ,所以有些东西正在失去这个背景。

最佳答案

当将 myObj.method2 方法作为参数传递给 app.post 时,您并没有告诉它应该在哪个上下文/范围内执行。因此它将在全局范围内执行。解决方案应该是 myObj.method2.bind(myObj)

关于javascript - 在原型(prototype)方法中使用 'this' 时丢失上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23661248/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com