最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

understanding javascript inheritance and node.js util inherits function example - Stack Overflow

programmeradmin0浏览0评论

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();

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();
Share Improve this question asked Mar 19, 2013 at 6:55 kenneth koontzkenneth koontz 8691 gold badge9 silver badges16 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 13

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() { }
发布评论

评论列表(0)

  1. 暂无评论