私は Node.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);
}
};
var mo = new myobj('hello world!');
mo.indexpage();
私の結果は期待通りです:
a test
hello world!
同じコードを取得して、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 コード
var MyObj = require('myobj.js');
var mo = new MyObj('hello world!');
mo.indexpage();
今私は得るTypeError: Object #<Object> has no method 'indexpage'
どこが間違っていますか?私はこの 1 つの問題に何時間も取り組んできました。JavaScript の基本的な知識は、フォーラムを検索する以上に、この問題を理解するのに役立ちません。