Creating "new" objects on Node.Js

This question already has an answer here:

  • What is the 'new' keyword in JavaScript? 13 answers

  • 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").


    如果不使用新关键字,则可能表示它们在需要时返回新对象。

    链接地址: http://www.djcxy.com/p/40868.html

    上一篇: 了解“this”关键字的范围

    下一篇: 在Node.Js上创建“新”对象