I'm working through Node.js module, but I'm stuck on how to export a prototype in a way that makes the methods accessible.
For example, take the following code:
var myobj = function(param) {
this.test = 'a test';
return this.param = param;
};
myobj.prototype = {
indexpage: function() {
console.log(this.test);
return console.log(this.param);
}
};
var mo = new myobj('hello world!');
mo.indexpage();
My results are as expected:
a test
hello world!
If I take the same code and place it in another file with module.exports:
somefile.js
var myobj = function(param) {
this.test = 'a test';
return this.param = param;
};
myobj.prototype = {
indexpage: function() {
console.log(this.test);
return console.log(this.param);
}
};
// the only line that is different
module.exports = myobj;
app.js code
var MyObj = require('myobj.js');
var mo = new MyObj('hello world!');
mo.indexpage();
Now I get TypeError: Object #<Object> has no method 'indexpage'
Where am I going wrong? I've been working on this single issue for hours; my basic grasp of javascript isn't helping me figure out this issue any more than searching forums.
You are returning a value from your constructor function.
var myobj = function(param) {
this.test = 'a test';
return this.param = param;
};
should be:
var myobj = function(param) {
this.test = 'a test';
this.param = param;
};
Because of the return, what you are really doing is
var mo = 'hello world!';
mo.indexpage();