Search code examples
javascriptdesign-patternsfactory-pattern

What's the difference between these two function declarations in Javascript?


I have some doubt about this two javascript case:

function some() {
    this.some2 = function() {//this is associated with own object(Correct?)
        console.log('some2');
    }
}

var __s1 = new some();
__s1.some2();//Allright, this do the work;
//some().some2();//This not work

This declaration type has a technical name? Object patterns maybe?

Another similiar case is this:

function some() {
    return {
        some2: function() {
            console.log('some2');
        }
    }
}

var __s2 = new some();
__s2.some2(); // Right, this work;
some().some2(); //Also work ... Ok, "some()" returns a object that contain
                //the some2().

This second case, also has a technical name?

What's best case between they?


Solution

  • The first one is using Prototypes. Calling new some() creates a new object, sets this to that object during the function execution, and returns the new object. Calling some() is meaningless in this case because there will be nothing to set this to when some is being executed (though the function still does get executed.)

    The second case is a normal function that returns an object. There is no technical name for it.

    Similar to the second case, is something called Closures. You could do,

    function some() {
        return function() {
            console.log('some2');
    
        }
    

    and then do

    var s3= some();
    s3() //prints some2