antonjs
antonjs

Reputation: 14338

Better way for writing JavaScript function

The following ways of writing a javascript function are equivalent.

Maybe the first one is more clear.

Nevertheless, many programmers prefer the second way.

There are significant difference between the two ways for preferring the second-one?

First way:

Class.prototype.fn = function () {
        var obj = { 
            … 
        };

        return obj;
};

Second way:

Class.prototype.fn = function () {

        return {
            .........
          };
};

Upvotes: 0

Views: 637

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075925

Unless you need to perform an operation on obj after creating it via the literal, there's no difference and it's just a subjective style preference. (Note that said use could be in the code, or during debugging; more below.)

So for example, there's a real practical difference here:

Class.prototype.fn = function () {
        var obj = { 
            subordinate: {
                foo: function() {
                    if (obj.flag) {
                        doOneThing();
                    }
                    else {
                        doSomethingElse();
                    }
                }
            }
        };

        return obj;
};

There, you need the name, so that obj.subordinate.foo() works. (Not that I'd advocate doing this, but it's an example of when there's an objective rather than subjective distinction.) But barring needing to use it after initialization and before return, it's just a subjective thing.

Of course, that use need not necessarily be in the code. The form with the obj variable can be more useful when debugging, if you need to inspect what you're returning before you return it.


Perhaps going a bit off-piste here, but I think it's related: In contrast to the examples in your question, there's a real, practical, tangible difference between this:

Class.prototype.foo = function () {
        … 
};
Class.prototype.bar = function () {
        … 
};

and this:

(function() {
    function Class_foo() {
            … 
    }
    function Class_bar() {
            … 
    }

    Class.prototype.foo = Class_foo;
    Class.prototype.bar = Class_bar;
})();

...that difference being that in the former, the functions have no names (the properties referring to them do, but not the functions themselves). In the latter case, the functions have real names, which help your tools help you by showing you names in call stacks, lists of breakpoints, etc.

Upvotes: 7

Related Questions