Answer the question
In order to leave comments, you need to log in
JavaScript is killing me [Node.js]
I don't even know how to ask a question, but
var model1 = new require('./test/model1')();
var model2 = new require('./test/model2')();
model1.test();
model2.test();
module.exports = function() {
var self = this;
self.test = function() {
console.log("MODULE 1");
}
return self;
}
module.exports = function() {
var self = this;
self.test = function() {
console.log("MODULE 2");
}
return self;
}
MODULE 2
MODULE 2
Answer the question
In order to leave comments, you need to log in
It's not a bug or a feature, you're just using this incorrectly.
When you call the this = function on a global object, that's why there are errors, you need to write model = new require(....). I advise you to read, for example, here, about the use of this and functions: javascript.ru/tutorial/object/thiskeyword (although the explanation there is so-so)
// m1.js
module.exports.Model = function() {
this.test = function() {
console.log("MODULE 1");
};
};
// m2.js
module.exports.Model = function() {
this.test = function() {
console.log("MODULE 2");
};
};
//test.js
var model1 = new (require('./lib/m1.js').Model);
var model2 = new (require('./lib/m2.js').Model);
model1.test();
model2.test();
//result
MODULE 1
MODULE 2
The problem of precisely this misunderstanding of yours, as far as I can see it, is solved by a thoughtful reading of the manual on operator precedence , used in the JavaScript language. After that, understanding will come, a state of comprehensive clarity will come.
operators
As you can see function call below the new operator, and if you highlight your entry with brackets, then the interpreter does the following -
var model1 = (new require('./test/model1'))();
self == model1 == model2 == global
var module = new (require('module'))();
// екзотические варианты -
var module = new require('module').prototype.constructor();
var module = new new require('module')();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question