0

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?

Constantin Groß
  • 10,719
  • 4
  • 24
  • 50
user3854612
  • 127
  • 1
  • 1
  • 7
  • doesnt answer your question but relevant http://stackoverflow.com/questions/1809914/oo-javascript-constructor-pattern-neo-classical-vs-prototypal – Daniel Lizik Mar 21 '17 at 19:58

2 Answers2

1

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
0

In your first snippet you associate a function to a property named some2.

In JS functions are first class object so they can have additional properties, when you call some2 you actually use object delegation on some function.

In your second snippet you are using return to return a new completely object at every call which has a new function some2. When you initiate a new object based (new some()) you actually return new objects with new functions and do not referencing to a single one as in your first snippet.

GibboK
  • 71,848
  • 143
  • 435
  • 658