0

recently i've been watching a video-tutorials of node.js. And on the part of "Object factory".

var foo = require("./module");

and he create an "new object" doing this

var myObject = foo();

now he can use all the methods within of foo module. why he not use the "new" word?

var myObject = new foo();
  • Can you not access all of the methods by referencing foo itself without creating a new object? – Daniel K. Jun 17 '15 at 21:00
  • 1
    A function can return an object with methods on it without being a constructor function. – Quentin Jun 17 '15 at 21:02
  • This isn't a node.js thing but how JavaScript handles object creation and contructors. You can check out [MDN's documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new) and/or you can also read [**You Don't Know JS: *this* & Object Prototypes**](http://amzn.to/1RagwFf), specifically [this section](https://github.com/getify/You-Dont-Know-JS/blob/fe5ee5db541c6a35b67561caaa5c125d99c5ab4c/this%20%26%20object%20prototypes/ch5.md#class-functions). – Jason Cust Jun 17 '15 at 21:07
  • @Quentin yeah i get it!, `module.exports = function(){ return { hw : "Hello Wordl"}}`. without the `return` I need to use `new`, isn't? – Ezequiel Durán Jun 17 '15 at 21:09
  • 1
    @EzequielDurán — The function would need to be designed to be used with new. Simply leaving out return isn't enough. – Quentin Jun 17 '15 at 21:12

2 Answers2

0

Take this for example:

function SomeClass() {}
SomeClass.prototype = {
    sayHi: function() {
        console.log('hello');
    }
};

function foo() {
    return new SomeClass();
}

foo() // => returns a new SomeClass object

In that case, foo is what they're referring to as a "factory" function, in that it is sort of like a type of factory that creates objects (just like in real life how factories create new objects; car factories, etc.)

It's also good for singletons:

(function() {
    var singleton;

    function SomeClass() {}
    SomeClass.prototype = {
        sayHi: function() {
            console.log('hello');
        }
    };

    function foo() {
        singleton = singleton || new SomeClass();
        return singleton;
    }

    window.foo = foo;
}());

foo(); // returns a new SomeClass
foo(); // returns the same SomeClass instance (not a new one). This is a singleton.

Node.js is just regular JavaScript, so in the example you've given, all you're doing is including the factory from a module and using it to create new objects (instances of "classes").

Josh Beam
  • 19,292
  • 3
  • 45
  • 68
0

Without the use of the new keyword could indicate they return a new object when you require it.