Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs Modules instanceof

I have simple module query.js:

module.exports = function(queryString){
     return{
         string: queryString
     };
};

Now I am loading this module from another module and create instance out of it:

var Query = require("./query");
var myQuery = new Query("SELECT * FROM `mytabel`");

console.log(myQuery instanceof Query); // Ouputs false
console.log(myQuery.constructor == Query); // Outputs false

As I understood from the nodejs documentation, require("Query") gives me module.exports object which in my case is anonymous function that accepts 1 parameter queryString. I use this function to create new object myQuery and yet, it is not instance of Query.

MY QUESTION: How can I check if myQuery is created from the Query function and why are both outputs false when they should be true in my opinion?

like image 833
Tauri28 Avatar asked Feb 15 '23 18:02

Tauri28


1 Answers

While dskh is correct, a little more explanation might be valuable.

A function can only act as a constructor when it returns something else than an Object.

Once a function returns an Object (e.g. function SomeFunc() { return {}; }), if you call var a = new SomeFunc();, variable a will become the returned Object, which is a plain Object, and will not be a created instance of SomeFunc. If SomeFunc returned something else than an Object, the JS engine would ignore whatever the function returns and instead return an Object of instance SomeFunc, which is what you want.

So in your case, you return an Object, but in order to make it work as a constructor you need to return nothing (or at least anything else than an Object):

module.exports = function(queryString){
     this.string = queryString;
};

See, it does not return an Object, so you will get an instance of Query everytime you call new Query().

like image 93
Willem Mulder Avatar answered Feb 17 '23 20:02

Willem Mulder