简体   繁体   English

node.js返回未定义的问题

[英]node.js returns undefined issue

Any ideas why I am getting undefined when I try to output helpers.limitsOfToday.todayStart ? 当我尝试输出helpers.limitsOfToday.todayStart时,为什么我undefined任何想法? If I try to output helpers.limitsOfToday I can see the function. 如果我尝试输出helpers.limitsOfToday ,则可以看到该函数。

This is my code: 这是我的代码:

helpers.js file helpers.js文件

const limitsOfToday = () => {
    var todayStart = new Date();
    todayStart.setHours(0, 0, 0, 0);

    var todayEnd = new Date();
    todayEnd.setHours(23, 59, 59, 999);

    return {
        todayStart: todayStart,
        todayEnd: todayEnd,
    }
};

module.exports = { limitsOfToday };

other file 其他档案

const helpers = require('./helpers.js');
helpers.limitsOfToday.todayStart // this is undefined

The property limitsOfToday is a function and you are returning todayStart as a key of the returning object. 属性limitsOfToday是一个函数,您要返回todayStart作为返回对象的键。

Execute limitsOfToday and everything should work like expected: 执行limitsOfToday ,一切应该按预期工作:

const helpers = require('./helpers.js');
helpers.limitsOfToday().todayStart; // your start date

In helpers.js file write helpers.js文件中写入

module.exports = limitsOfToday; 

and in other file 和其他文件

helpers().todayStart

Another solution is to write in helpers.js file 另一个解决方案是写入helpers.js文件

module.exports = {limitsOfToday: limitsOfToday}; 

and in other file 和其他文件

helpers.limitsOfToday().todayStart

You are exporting object with limitsOfToday method which is just a function so when you write helpers.limitsOfToday.todayStart you are trying to access property todayStart of object's method which doesn't work. 您正在使用limitsOfToday方法导出对象,而limitsOfToday方法只是一个函数,因此当您编写helpers.limitsOfToday.todayStart您试图访问对象方法的todayStart属性,该方法无效。 What you need to do is call 您需要做的就是打电话

helpers.limitsOfToday().todayStart

so that limitsOfToday method returns object with todayStart property that you can access. 这样limitsOfToday方法将返回具有todayStart访问属性的对象,您可以访问该对象。

将您的最后一行更新为类似于此module.exports = { limitsOfToday: limitsOfToday() };

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

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