I have two files: BaseController.js and EventRecordController.js. EventRecord needs to inherit a few methods from BaseController.
BaseController
var Q = require('q'),
util = require('../util');
exports.BaseController = function(req, res) {
this.req = res;
this.res = res;
this.fields = {};
this.error = {
code: 200,
message: 'BAD REQUEST: The parameters provided were invalid. See response body for error messages.',
specific_message: ''
};
};
// Utility method to handle returning errors that are thrown.
exports.BaseController.prototype.handle_errors = function(error) {
if(this.error.code === 500) {
util.internal_error(this.res, this.response_type);
} else {
var response = util.build_error_response(this.response_type, this.error.code, this.error.message, this.error.specific_message);
util.send_response(this.res, this.response_type, this.error.code, response);
}
};
// Check to see if a user is authenticated and whether they are using a correct response type.
exports.BaseController.prototype.validate_response_type_and_authenticate = function() {
var deferred = Q.defer();
util.validate_response_type_and_authenticate(this.req, this.res, function(auth_data, response_type) {
this.auth_data = auth_data;
this.company_user_uid = this.auth_data.data.company.uid;
this.response_type = response_type;
this.v3_token = this.auth_data.data.token;
deferred.resolve();
});
return deferred.promise;
};
EventRecordController
var base_controller = require("./BaseController"),
Q = require('q'),
util = require('../util'),
validator = require('validator');
exports.EventRecordController = function(req, res) {
function EventRecord(req, res) {
base_controller.BaseController.apply(this, arguments);
}
// Inherit from BaseController, then fix constructor.
EventRecord.prototype = new base_controller.BaseController();
EventRecord.prototype.constructor = EventRecord;
EventRecord.run = function() {
console.log(this.error);
};
return EventRecord;
};
When I run the following code, this.error logs as undefined from within the run() method.
var event_record_controller = require("./controllers/EventRecordController"),
util = require('./util'),
validator = require('validator');
exports.record = function(req, res) {
var controller = new event_record_controller.EventRecordController(req, res);
controller.run();
};
I think I'm missing something obvious here, but my experience with prototype based inheritance is limited.
returns an object, the object created bynewwill be discarded. So,new EventRecordController()is returning thefunction EventRecordrather than an instance.EventRecordController? Then you're missing the IEFE callrunnot a function on theEventRecordprototype, but a "static" one?util.validate_response_type_and_authenticateis probably called with the wrongthiseither