javascript - 实例方法不在NodeJS中的JS模块范围内?
问题描述
我试图在 NodeJS 中创建一个非单例对象,但是在对象中调用内部实例方法时,它们是“未定义的”。
// We auto-refresh the cached data every 'refreshInterval' milliseconds
var refreshInterval = 30*1000;
var refreshTimer = null;
// We stop refreshing 'idleTimeout' milliseconds after the last request for our data
var idleTimeout = 5 * 60 * 1000; // 5 minutes
var idleTimer = null;
var cachedData = null;
var queryCallback = null;
function Cache(options) {
if (options) {
this.refreshInterval = options.refreshInterval || 30;
this.queryCallback = options.queryCallback || null;
this.idleTimeout = options.idleTimeout || 5 * 60 * 1000;
}
}
Cache.prototype.data = function(callback) {
updateIdle();
if (cachedData) {
callback(cachedData);
} else {
queryData(function(newdata) {
callback(newdata);
});
}
}
Cache.prototype.updateIdle = function() {
idleTimer && clearTimeout(idleTimer);
idleTimer = setTimeout(haltRefresh, idleTimeout);
wslog.info(`Will cease cache refresh at ${new Date(Date.now() + idleTimeout)} if no new activity`);
}
// ...
module.exports = Cache;
当我创建对象
var Cache = require('./cache.js');
var myCache = Cache(opts);
它可以工作,但是当我调用时myCache.data()
,内部方法的调用会updateIdle()
暂停应用程序,因为ReferenceError: updateIdle 未定义
有些事情告诉我,我的实例方法都不会被“定义”,即使它们显然是。在我制作prototype
方法之前,它们工作得很好。这些将是有效的 Java 实例方法调用 - JS 是否存在一些范围问题?
我应该Cache.prototype.
从不需要暴露的功能中删除然后使用它们吗?我必须添加this.
到任何实例方法调用吗?
我需要知道什么才能让 JS 像普通的 OOP 一样“正常工作”?
解决方案
推荐阅读
- javascript - 为什么我的 else-if Javascript 条件不起作用?
- python - 如何在 Django 中使用自动生成的 slug 作为发布 URL 链接
- css - Tailwind CSS 自定义断点不起作用
- php - spatie/laravel-analytics pageViews 在增加时间段时越来越多,即使页面是几天前的
- json - 如何从外部 API 访问 Json 字符串值?
- python - 有没有办法在 PCA/LDA 数据上放置圆/椭圆
- java - 为什么 JMH 会为简单的快速排序报告如此奇怪的时间——显然与 N * log(N) 不成比例?
- python - 在较长的字符串中查找几个不同字符串的第一次出现
- javascript - 如何使用 moment.js 循环遍历数组
- php - 在 Apache 或 PHP 中为 Web 服务器设置安全标头和 Cookie 属性?