Denis
Denis

Reputation: 2469

Difference between JavaScript methods structure

What is the difference between this method structures/callings?
I often see different method structures and I can not understand what the benefits of each are.

var obj = {
    some_method: function(){
        return 'This works';
    }
}

var Obj2 = function(){
    return {
        some_method: function(){
            return 'This works too';
        }
    }
}

console.log(obj.some_method());

var obj3 = new Obj2();
console.log(obj3.some_method());

Both of them return what they should, here's JsFiddle, but in what case I should use each of them?

Upvotes: 0

Views: 83

Answers (2)

Esailija
Esailija

Reputation: 140220

The first one resembles a singleton, I.E. you cannot have multiple objects of same type but with distinct state. Like it's only possible to have one actual animal in your entire application instead of many.

A more practical example, consider this page. There are multiple Posts, each with their own state (What Comments they have, what text they have, are they currently being edited and so on). If you just did var post = then that means there can only be one post. I suspect you will probably have some ad-hoc jQuery to manipulate multiple posts in that singleton but then you are not doing object oriented modeling of the problem anyway.


The second one is using constructor function incorrectly, the created objects will not be instances of Obj2 but Object. You would use a constructor like:

function Obj2() {
   //initialize fields here
}

Obj2.prototype.someMethod = function(arg) {
     return this.state + arg;
};

The reason returning object literal works in a constructor is that a constructor is allowed to return objects of any type. But it doesn't make sense to make a constructor only to return Objects.

You typically need Objects only for grouping related static functionality together (behavior, but no prolonged data) or as a dictionary/map/associative array (data but no behavior).

Upvotes: 1

Joseph
Joseph

Reputation: 119847

In the first code, you are calling obj.some_method(). some_method is a function, nested as a property of obj. This pattern is one way of namespacing.

In the second case, you are creating an object, using Obj2 as a constructor. However, instead of returning an instance of Obj2, you returned an object which has the same structure as the previous example's obj. This will give you erroneous results from instanceof tests, since new Obj2 should return an instance of itself, which your code isn't doing.

Upvotes: 0

Related Questions