node.js中module.parent的用途是什么?如何引用require()ing模块? [英] What is the use of module.parent in node.js? How can I refer to the require()ing module?

查看:102
本文介绍了node.js中module.parent的用途是什么?如何引用require()ing模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在查看 node.js模块文档,发现每个模块都有一个属性-module.parent .我尝试使用它,但是被模块缓存烧死了-module.parent似乎只在 first require()'的模块中出现,而与当前上下文无关.

I was looking in the node.js module documentation, and noticed that each module has a property- module.parent. I tried to use it, but got burnt by the module caching- module.parent only ever seems to the module that first require()'d it, irrespective of current context.

那么它的用途是什么?我还有其他方法可以获取对 current require()ing模块的引用吗?现在,我将模块包装在一个函数中,因此它的名称如下:

So what is the usage of it? Is there any other way for me to get a reference to the current require()ing module? Right now I'm wrapping the module in a function, so that it is called like:

require("mylibrary")(module)

但这似乎不是最理想的.

but that seems sub-optimal.

推荐答案

父级"是导致脚本被解释(和缓存)的模块,如果有的话:

The "parent" is the module that caused the script to be interpreted (and cached), if any:

// $ node foo.js
console.log(module.parent); // `null`

// require('./foo')
console.log(module.parent); // `{ ... }`

您期望的是呼叫者",Node不会为您保留该呼叫者.为此,您需要当前使用的导出函数作为该值的闭包.

What you're expecting is the "caller," which Node doesn't retain for you. For that, you'll need the exported function you're currently using to be a closure for the value.

这篇关于node.js中module.parent的用途是什么?如何引用require()ing模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆