Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

understanding javascript inheritance and node.js util inherits function example

I have two modules: apirequest.js and feed.js. When I call feed.start() in apirequest, I get, TypeError: Object #<Feed> has no method 'start'. Why is this? Doesn't util.inherits(Feed, APIRequest); inherit APIRequest's properties?

apirequest.js

var EventEmitter = require('events').EventEmitter;
var util = require('util');

function APIRequest(endpoint) { } 

APIRequest.prototype.start = function() { }

util.inherits(APIRequest, EventEmitter);

module.exports = APIRequest;

feed.js

var util = require('util');
var APIRequest = require('../lib/api_request');

function Feed(endpoint) {
  APIRequest.call(this, endpoint);
}

util.inherits(Feed, APIRequest);

var feed = new Feed(endpoint);

feed.start();
like image 260
kenneth koontz Avatar asked Mar 19 '13 06:03

kenneth koontz


1 Answers

The problem is order:

APIRequest.prototype.start = function() { }
util.inherits(APIRequest, EventEmitter); <-- *overwrites* APIRequest.prototype

If you swap those lines, it'll work:

util.inherits(APIRequest, EventEmitter);
APIRequest.prototype.start = function() { }
like image 90
robertklep Avatar answered Oct 20 '22 04:10

robertklep