首页 > 解决方案 > 实例方法不在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 一样“正常工作”?

标签: javascriptnode.jsoopmodulescope

解决方案


推荐阅读