M
M
max_mara2013-05-09 03:48:04
JavaScript
max_mara, 2013-05-09 03:48:04

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


model1.js
module.exports = function() {
    var self = this;

    self.test = function() {
        console.log("MODULE 1");
    }

    return self;
}

model2.js
module.exports = function() {
    var self = this;

    self.test = function() {
        console.log("MODULE 2");
    }

    return self;
}


As a result
MODULE 2
MODULE 2


It turns out that the test() function from the second module overwrites the function with the same name in the first module.
How so? Is this a bug or a feature?
And how to solve my problem?

Thanks and sorry for the confusion.

Okay, okay, I got it. I was wrong. Thank you very much for the help!

Answer the question

In order to leave comments, you need to log in

4 answer(s)
E
egorinsk, 2013-05-09
@max_mara

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)

S
Stdit, 2013-05-09
@Stdit

// 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

M
Mithgol, 2013-05-09
@Mithgol

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.

A
Alexander Keith, 2013-05-09
@tenbits

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

The require function will work well, even regardless of what context it was called - and the subsequent function call will already be in the global context
self == model1 == model2 == global
Different solutions:
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 question

Ask a Question

731 491 924 answers to any question