【问题标题】:expressjs server.js this is undefined, how can I refer to serverexpressjs server.js 这是未定义的,我怎么能引用服务器
【发布时间】:2019-03-21 05:26:46
【问题描述】:

在 ExpressJS 设置中,我有 server.js,我在其中执行以下操作:

import { call_method } from '../hereIam.mjs';

const process_db = async () => {
  console.log(this); // undefined
  call_method(this);
};

console.log(this) // undefined
process_db();

然后,我想从hereIam.mjs 调用父方法,但这是未定义的

export const call_method = parent_this => console.log(parent_this); // undefined 

我试图在 server.js 中包含类,以试图强制拥有 this

class AppServer {
 constructor() {
   console.log(this)
 }

 const process_db = async () => call_method(this);
}

但似乎类中的箭头函数无法在(实验性)NodeJS中编译(这应该是另一个问题)

已编辑

我如何做到这一点是避免使用箭头符号以便能够在 Express 中使用类,然后实例化一个提供 this 的类。

class AppServer {
 async process_db() {call_method(this)};
}

let server = new AppServer();
server.process_db();

问题是,获得this 引用的唯一方法是使用对象/类?

【问题讨论】:

  • 不,在讨论箭头之前这是未定义的。我现在正在编辑问题
  • 记住,作用域是在你使用new关键字时创建的
  • 哦,谢谢,这是关于新的,谢谢!
  • 是的,您需要函数或类才能拥有 this 对象。 Lambda 函数使用其外部作用域。所以它将在其外部范围内使用它。

标签: javascript node.js express this


【解决方案1】:

您可以使用bind 方法并传递任何对象以用作this 上下文。

但是,箭头函数从调用它们的地方接收上下文,function() {} 函数语法使用绑定到它们的上下文,或者通过它们定义的上下文隐式地绑定到它们,或者显式地使用这个 bind em> 方法。

因此,使用类的替代方法是将简单对象绑定到方法,例如:

const call_method = require('../hereIam.mjs');

const process_db = async function() {
  console.log(this); 
  call_method(this);
};

console.log(this);

const context = {
    name: 'bound context',
    parent_method: async function() {
        console.log('Good evening');
    }
}

process_db.bind(context)();

假设hereIam.mjs 包含:

module.exports = parent_this => console.log(parent_this);

然后脚本会输出:

{}
{ name: 'bound context',
  parent_method: [AsyncFunction: parent_method] }
{ name: 'bound context',
  parent_method: [AsyncFunction: parent_method] }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多