简体   繁体   English

如何访问module.exports中的对象属性

[英]How to access object property in module.exports

I am curious about how to access another object property in module.exports. 我很好奇如何访问module.exports中的另一个对象属性。

here is the case : 情况是这样的:

 module.exports = { text: 'abcd', index: (req, res)=>{ console.log(text) <-- is not defined console.log(this.text) <-- undefined } } 

well then, how to access the text property? 那么,如何访问text属性? thanks guys need your explanation. 谢谢你们需要你的解释。

Javascript does not have a built-in way to refer to other properties in the same object. Javascript没有内置的方式来引用同一对象中的其他属性。 There are good reasons why it cannot do this for any arbitrary property. 有充分的理由为什么它不能对任何任意属性执行此操作。 So, you either have to make sure that this has the right object value in it or you need to save the appropriate object reference yourself somewhere that you can get to it. 所以,你要么必须确保this有它的正确对象的值或者您需要保存适当的对象引用自己的地方,你可以得到它。

Here's a way where you save the object reference yourself which works fine for a singleton object: 这是您自己保存对象引用的一种方法,该方法对于单例对象可以正常工作:

let myObj = {

 text: 'abcd',
 index: (req, res)=>{
   console.log(myObj.text)
 }

}

module.exports = myObj;

If you know that .index() will always be called appropriately as a method on your module.exports (which would be the usual case), then you can stop using the => definition and use a normal function definition (which should pretty much always be used for method declarations) and then this will have the desired value. 如果您知道.index()将始终作为module.exports上的方法被适当地调用(这是通常的情况),那么您可以停止使用=>定义并使用普通的function定义(这应该非常总是被用于方法声明),然后this将具有所需的值。

module.exports = {

 text: 'abcd',
 index: function(req, res) {
   console.log(this.text)
 }
}

This will work as long as .index() index is called like this: 只要像这样调用.index()索引,此方法就可以工作:

let myModule = require('myModule');
myModule.index(req, res);

People tend to fall in love with the arrow syntax and forget that it should pretty much NEVER be used for method definitions because it does NOT set this to the host object which creates problems for methods. 人们往往在爱上箭头语法和忘记,它应该几乎从不使用方法定义,因为它不设置this为其创建方法问题的宿主对象。 Instead, use the regular function definition for methods of an object. 而是将常规function定义用于对象的方法。


Arrow functions are typically very useful for callback functions where you want the callback to have access to the this value from your environment (called the lexical value of this ). 箭头函数通常对于希望回调能够从您的环境访问this值(称为this的词法值)的回调函数非常有用。 Here are some useful examples: 以下是一些有用的示例:

class Timer {
    delay(t, cb) {
       this.timer = setTimeout(() => {
           // preserve this value inside a callback
           this.timer = null;
           cb();
       })
    }
}

Or 要么

// preserve this value inside a callback
let filtered = myArray.filter(item => {
    return item.id !== this.master.id;
});

On the other hand, you pretty much never want to use an arrow declaration for a method because that will override the usual object value for this and replace it with a lexical value for this . 在另一方面,你几乎从来没有想用一个箭头声明的方法,因为这将覆盖通常对象值this与一个词汇值替换this

Try this 尝试这个

module.exports = {

        text: 'abcd',
        index: function (req,res) {
            console.log(this.text)
        }
    }

accessing via 通过访问

var te=require('modulename')
    te.index()

如何修复“无法分配给 object 的只读属性“导出”'#<object> ' 将第二个 function 添加到 module.exports 时?<div id="text_translate"><p> 不幸的是,我已经被困了大约 5 天了。 我用谷歌搜索过,没有什么对我有用。 我有一个 utils.js 文件,里面有很多东西可以帮助我。 当我将 function "doesUserContainRoles" 添加到导出时,我的 Chrome 控制台给了我错误:</p><blockquote><p> Uncaught TypeError: Cannot assign to read only property 'exports' of object '#&lt;Object&gt;'</p></blockquote><p> 当我删除 function 时,utils 文件中的所有内容都可以完美运行,根本没有 0 个问题。 只要我添加 function,我就会收到此错误。 我通过以下方式要求 utils 文件:</p><pre class="lang-js prettyprint-override"> const utils = require("../../../utils");</pre><p> 并且没有与此一起使用的import 。 (我知道module.exports和import不能一起工作)</p><p> 我正在使用什么:</p><ul><li><p> Vue.js @vue/cli 4.5.8</p></li><li><p> Node.js v15.2.0</p></li></ul><h3> 文件:</h3><p> utils.js</p><pre class="lang-js prettyprint-override"> const winston = require("winston"); const { datadog } = require("./credentials.js"); const { createLogger, format, transports } = require('winston'); const base_url = "http://localhost:3001/api/v1" // Winston ~ const httpTransportOptions = { host: datadog.logger.host, path: datadog.logger.path, ssl: datadog.logger.ssl }; const customLevels = { levels: { emergency: 0, alert: 1, critical: 2, error: 3, warn: 4, notice: 5, info: 6, debug: 7, success: 8 }, } const logger = createLogger({ level: 'info', levels: customLevels.levels, exitOnError: false, format: format.json(), transports: [ new transports.Http(httpTransportOptions), ], }); const commonMessages = { accessPage: "User Accessed a Page", restrictedPage: "Attempt at accessing restricted page" } function alertGeneral() { alert("Oops. An error has occurred. Please try again later, If this problem continues. please contact Vinniehat;"), } function doesUserContainRoles(userRoles. containsRoles) { return.;userRoles.some(role =&gt; containsRoles,includes(role)), } module,exports = { logger, commonMessages, base_url, alertGeneral, doesUserContainRoles }</pre><p> 这是错误堆栈:</p><pre> Uncaught TypeError: Cannot assign to read only property 'exports' of object '#&lt;Object&gt;' at Module.eval (utils.js?1b23:45) at eval (utils.js:68) at Module../utils.js (app.js:1944) at __webpack_require__ (app.js:854) at fn (app.js:151) at eval (router.js?9883:19) at Module../src/router/router.js (app.js:1812) at __webpack_require__ (app.js:854) at fn (app.js:151) at eval (main.js:34)</pre><p> 我也尝试使用export default 。 这样做时,我的前端工作。 网站加载没有错误。 不过,我的后端使用 Express.js 运行,然后引发错误:</p><pre> Unhandled rejection E:\Development\Websites\iceberg-gaming-website\utils.js:45 export default { ^^^^^^ SyntaxError: Unexpected token 'export' at wrapSafe (node:internal/modules/cjs/loader:1018:16) at Module._compile (node:internal/modules/cjs/loader:1066:27) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1131:10) at Module.load (node:internal/modules/cjs/loader:967:32) at Function.Module._load (node:internal/modules/cjs/loader:807:14) at Module.require (node:internal/modules/cjs/loader:991:19) at require (node:internal/modules/cjs/helpers:92:18) at Object.&lt;anonymous&gt; (E:\Development\Websites\iceberg-gaming-website\express\modules\user.js:9:15) at Module._compile (node:internal/modules/cjs/loader:1102:14) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1131:10) at Module.load (node:internal/modules/cjs/loader:967:32) at Function.Module._load (node:internal/modules/cjs/loader:807:14) at Module.require (node:internal/modules/cjs/loader:991:19) at require (node:internal/modules/cjs/helpers:92:18) at E:\Development\Websites\iceberg-gaming-website\express\express.js:27:27 at tryCatcher (E:\Development\Websites\iceberg-gaming-website\node_modules\bluebird\js\release\util.js:16:23)</pre></div></object> - How do I fix 'Cannot assign to read only property 'exports' of object '#<Object>' when adding a 2nd function to module.exports?

暂无
暂无

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

相关问题 如何在module.exports 中运行属性? - how to run property in module.exports? module.exports与对象 - module.exports with object 如何从module.exports访问函数 - How to access function from module.exports 如何修复“无法分配给 object 的只读属性“导出”'#<object> ' 将第二个 function 添加到 module.exports 时?<div id="text_translate"><p> 不幸的是,我已经被困了大约 5 天了。 我用谷歌搜索过,没有什么对我有用。 我有一个 utils.js 文件,里面有很多东西可以帮助我。 当我将 function "doesUserContainRoles" 添加到导出时,我的 Chrome 控制台给了我错误:</p><blockquote><p> Uncaught TypeError: Cannot assign to read only property 'exports' of object '#&lt;Object&gt;'</p></blockquote><p> 当我删除 function 时,utils 文件中的所有内容都可以完美运行,根本没有 0 个问题。 只要我添加 function,我就会收到此错误。 我通过以下方式要求 utils 文件:</p><pre class="lang-js prettyprint-override"> const utils = require("../../../utils");</pre><p> 并且没有与此一起使用的import 。 (我知道module.exports和import不能一起工作)</p><p> 我正在使用什么:</p><ul><li><p> Vue.js @vue/cli 4.5.8</p></li><li><p> Node.js v15.2.0</p></li></ul><h3> 文件:</h3><p> utils.js</p><pre class="lang-js prettyprint-override"> const winston = require("winston"); const { datadog } = require("./credentials.js"); const { createLogger, format, transports } = require('winston'); const base_url = "http://localhost:3001/api/v1" // Winston ~ const httpTransportOptions = { host: datadog.logger.host, path: datadog.logger.path, ssl: datadog.logger.ssl }; const customLevels = { levels: { emergency: 0, alert: 1, critical: 2, error: 3, warn: 4, notice: 5, info: 6, debug: 7, success: 8 }, } const logger = createLogger({ level: 'info', levels: customLevels.levels, exitOnError: false, format: format.json(), transports: [ new transports.Http(httpTransportOptions), ], }); const commonMessages = { accessPage: "User Accessed a Page", restrictedPage: "Attempt at accessing restricted page" } function alertGeneral() { alert("Oops. An error has occurred. Please try again later, If this problem continues. please contact Vinniehat;"), } function doesUserContainRoles(userRoles. containsRoles) { return.;userRoles.some(role =&gt; containsRoles,includes(role)), } module,exports = { logger, commonMessages, base_url, alertGeneral, doesUserContainRoles }</pre><p> 这是错误堆栈:</p><pre> Uncaught TypeError: Cannot assign to read only property 'exports' of object '#&lt;Object&gt;' at Module.eval (utils.js?1b23:45) at eval (utils.js:68) at Module../utils.js (app.js:1944) at __webpack_require__ (app.js:854) at fn (app.js:151) at eval (router.js?9883:19) at Module../src/router/router.js (app.js:1812) at __webpack_require__ (app.js:854) at fn (app.js:151) at eval (main.js:34)</pre><p> 我也尝试使用export default 。 这样做时,我的前端工作。 网站加载没有错误。 不过,我的后端使用 Express.js 运行,然后引发错误:</p><pre> Unhandled rejection E:\Development\Websites\iceberg-gaming-website\utils.js:45 export default { ^^^^^^ SyntaxError: Unexpected token 'export' at wrapSafe (node:internal/modules/cjs/loader:1018:16) at Module._compile (node:internal/modules/cjs/loader:1066:27) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1131:10) at Module.load (node:internal/modules/cjs/loader:967:32) at Function.Module._load (node:internal/modules/cjs/loader:807:14) at Module.require (node:internal/modules/cjs/loader:991:19) at require (node:internal/modules/cjs/helpers:92:18) at Object.&lt;anonymous&gt; (E:\Development\Websites\iceberg-gaming-website\express\modules\user.js:9:15) at Module._compile (node:internal/modules/cjs/loader:1102:14) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1131:10) at Module.load (node:internal/modules/cjs/loader:967:32) at Function.Module._load (node:internal/modules/cjs/loader:807:14) at Module.require (node:internal/modules/cjs/loader:991:19) at require (node:internal/modules/cjs/helpers:92:18) at E:\Development\Websites\iceberg-gaming-website\express\express.js:27:27 at tryCatcher (E:\Development\Websites\iceberg-gaming-website\node_modules\bluebird\js\release\util.js:16:23)</pre></div></object> - How do I fix 'Cannot assign to read only property 'exports' of object '#<Object>' when adding a 2nd function to module.exports? Object.assign(module.exports, {…}) vs module.exports = {…} - Object.assign(module.exports, {…}) vs module.exports = {…} 正在导出从module.exports返回的对象 - Is exports an object returned from module.exports 如何使用 module.exports 从另一个文件访问 object.prototype 方法? - How to access object.prototype methods from another file using module.exports? 如何访问 module.exports 声明中的函数? - How to access functions that are inside a module.exports declaration? JS - 如何在同一文件中访问module.exports函数 - JS - How to access a module.exports function in the same file 如何返回猫鼬对象字段(在Module.exports函数中) - How to Return Mongoose Object Field (In Module.exports function)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM