简体   繁体   English

使用导出的函数时无法读取未定义的属性

[英]Cannot read property of undefined when using exported function

I have the following Express app: 我有以下Express应用:

router.js router.js

var express = require('express');
var router = express.Router();
var exch = require("../exchanges/exch")();

router.get('/', function(req, res, next) {

    exch .getTicker((tick) => {
        res.send('get ticker exch: ' + JSON.stringify(tick));
    });

});

module.exports = router;

exch.js exch.js

var Kraken = require('kraken-api');
var moment = require('moment');
var _ = require('lodash');

/**
...code
**/

var Exchange = function(config) {
  _.bindAll(this);

  if(_.isObject(config)) {
    this.key = config.key;
    this.secret = config.secret;
    this.currency = config.currency.toUpperCase()
    this.asset = config.asset.toUpperCase();
  }

  this.pair = addPrefix(this.asset) + addPrefix(this.currency);
  this.name = 'kraken';
  this.since = null;

  this.kraken = new Kraken(this.key, this.secret);
}

Exchange.prototype.getTicker = function(callback) {
  var set = function(err, data) {
    if(!err && _.isEmpty(data))
      err = 'no data';

    else if(!err && !_.isEmpty(data.error))
      err = data.error;

    if (err)
      return console.log('unable to get ticker' + JSON.stringify(err));

    var result = data.result[this.pair];
    var ticker = {
      ask: result.a[0],
      bid: result.b[0]
    };
    callback(err, ticker);
  };

  this.kraken.api('Ticker', {pair: this.pair}, _.bind(set, this));
};

}

module.exports = Exchange;

As you can see I am including the object via require("...")() . 如您所见,我正在通过require("...")()包含对象。 However, I still get the following error: 但是,我仍然收到以下错误:

Cannot read property 'getTicker' of undefined 无法读取未定义的属性“ getTicker”

TypeError: Cannot read property 'getTicker' of undefined at /home/ubuntu/workspace/routes/ticker.js:20:9 at Layer.handle [as handle_request] (/home/ubuntu/workspace/node_modules/express/lib/router/layer.js:95:5) at next (/home/ubuntu/workspace/node_modules/express/lib/router/route.js:137:13) at Route.dispatch (/home/ubuntu/workspace/node_modules/express/lib/router/route.js:112:3) at Layer.handle [as handle_request] (/home/ubuntu/workspace/node_modules/express/lib/router/layer.js:95:5) at /home/ubuntu/workspace/node_modules/express/lib/router/index.js:281:22 at Function.process_params (/home/ubuntu/workspace/node_modules/express/lib/router/index.js:335:12) at next (/home/ubuntu/workspace/node_modules/express/lib/router/index.js:275:10) at Function.handle (/home/ubuntu/workspace/node_modules/express/lib/router/index.js:174:3) at router (/home/ubuntu/workspace/node_modules/express/lib/router/index.js:47:12) TypeError:无法在Layer.handle的/home/ubuntu/workspace/routes/ticker.js:20:9读取未定义的属性“ getTicker”(作为handle_request)(/ home / ubuntu / workspace / node_modules / express / lib / router /layer.js:95:5)在Route.dispatch(/home/ubuntu/workspace/node_modules/express/lib/router/route.js:137:13)下(/ home / ubuntu / workspace / node_modules / express /lib/router/route.js:112:3)位于/ home / ubuntu上的Layer.handle [作为handle_request](/home/ubuntu/workspace/node_modules/express/lib/router/layer.js:95:5) /workspace/node_modules/express/lib/router/index.js:281:22在Function.process_params(/home/ubuntu/workspace/node_modules/express/lib/router/index.js:335:12)在下一个(/在Function.handle(/home/ubuntu/workspace/node_modules/express/lib/router/index.js:174:3)上的home / ubuntu / workspace / node_modules / express / lib / router / index.js:275:10)在路由器上(/home/ubuntu/workspace/node_modules/express/lib/router/index.js:47:12)

Why is this error occurring and how can I fix it? 为什么会发生此错误,我该如何解决?

You're not creating an instance, thus you can't access a method on the prototype. 您没有创建实例,因此无法访问原型上的方法。 You're actually just calling the constructor function Exchange exported by exch.js . 您实际上只是在调用exch.js导出的构造函数Exchange Since the constructor function, when called directly, returns nothing (implicitly undefined ), you get the error: 由于直接调用构造函数时,不返回任何内容(隐式为undefined ),因此会出现以下错误:

var exch = require("../exchanges/exch")(); //exch is undefined because Exchange as a function returns nothing

This does not setup the prototype because you haven't constructed an object, just called the function. 这不会设置原型,因为您还没有构造对象,仅称为函数。 Instead, use new to construct a new Exchange object: 而是使用new构造一个新的Exchange对象:

var Exchange = require("../exchanges/exch");
var exch = new Exchange();

This will create a new Exchange object in which you can call getTicker from the prototype. 这将创建一个新的Exchange对象,您可以在其中从原型中调用getTicker Note: Make sure to pass config to the constructor! 注意:确保将config传递给构造函数!


Without new you could do a check in Exchange to see if you accidentally called it without new , and to return a new instance: 如果没有new ,则可以在Exchange进行检查,以查看是否不带new意外地调用了它,并返回一个新实例:

var Exchange = function(config) {
  if(!(this instanceof Exchange)) {
    return new Exchange(config);
  }
  //...
}

What this does is return a new instance of Exchange even if you called the function directly. 这样做是即使您直接调用该函数也将返回一个新的Exchange实例。 Now you could use: 现在您可以使用:

var exch = require("../exchanges/exch")();

But I would always prefer the former method of using new always for constructors. 但是我总是更喜欢使用将new 始终用于构造函数的前一种方法。

require("../exchanges/exch")() call the function rather than create a new instance, use new to instantiate in order to use the prototype . require("../exchanges/exch")()调用函数而不是创建新实例,请使用new实例化以便使用prototype The reason you got undefined is that the Exchange returns nothing. undefined的原因是Exchange返回任何内容。 You suppose it to be a constructor , but you call it as function 您假设它是一个constructor ,但您将其称为function

Use the code instead: 使用代码代替:

var exchModule = require("../exchanges/exch")
var exch=new exchModule()

change last line of your code in exch.js 在exch.js中更改代码的最后一行

exports.exchange = Exchange;

now modify in router.js 现在在router.js中进行修改

var exch = require("../exchanges/exch").exchange;

var exchObject= new exch();

now you can use exchObject object to call methods 现在您可以使用exchObject对象来调用方法

暂无
暂无

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

相关问题 使用function()时无法读取未定义的属性“控件” - Cannot read property 'controls' of undefined when using function() 无法读取未定义的属性“功能” - Cannot read property 'function' of undefined 无法读取未定义的属性“ [功能]” - Cannot read property '[function]' of undefined 无法读取未定义的属性[功能] - Cannot read property [function] of undefined TypeError 'Cannot read property/undefined' 使用 toString 属性时 - TypeError 'Cannot read property/undefined ' when using toString property “未定义不是函数,并且”无法读取未定义的属性“ init”” - “Undefined is not a function and ”Cannot read property 'init' of undefined" 使用Function调用DataTable并在单击时获取TD数据,但收到“无法读取未定义属性'0'”的错误 - Calling DataTable using Function and get the TD data when clicked, but receiving an error of "Cannot read property '0' of undefined" TypeError:无法读取未定义的属性“ 0”(使用在另一个函数中定义的平方时发生错误) - TypeError: Cannot read property '0' of undefined (error occured when using squares which is defined in another function) 触发云函数时“类型错误:无法读取未定义的属性‘子’” - “TypeError: Cannot read property 'child' of undefined” when triggering cloud function 触发功能时出现“未捕获的TypeError:无法读取未定义的属性'名称'” - “Uncaught TypeError: Cannot read property 'Name' of undefined” when triggered a function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM