简体   繁体   English

如何在 nodejs 中将 THIS 与 babel 一起使用?

[英]How can i use THIS with babel in nodejs?

In the past i could use:过去我可以使用:

var _this = this
...
exports.someFunction = function (req, res) {
    _this.create(someVar)
}
...
exports.create = (someVar) => {
//logic here
return something
}

But since i added BABEL to use GraphQl, package.json :但是由于我添加了 BABEL 来使用 GraphQl, package.json

"devDependencies": {
     "@babel/core": "^7.8.4",
     "@babel/node": "^7.8.4",
     "@babel/preset-env": "^7.8.4",
     "@babel/register": "^7.8.3"
   }

and the .babelrc file with:.babelrc文件:

{
   "presets": [
     [
       "@babel/env"
     ]
   ]
}

I get the error:我收到错误:

uncaughtException: Cannot read property 'create' of null uncaughtException: 无法读取 null 的属性“create”

Please let me know what I am doing wrong or what I can do in .babelrc to allow the use of this请让我知道我做错了什么或我可以在.babelrc 中做什么以允许使用

Thanks.谢谢。

Because you want to reference a function which is a property of exports , why not reference exports to get to it?因为您想引用作为exports属性的函数,为什么不引用exports来获取它呢? No need to depend on the calling context of the module:无需依赖模块的调用上下文:

exports.someFunction = function (req, res) {
    exports.create(someVar);
}

It sounds like a Babel module's top level is not called with a calling context, so this is undefined (just like it would be in strict mode).听起来像 Babel 模块的顶层没有用调用上下文调用,所以thisundefined (就像在严格模式下一样)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM