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 {
.........
};
};
Unless you need to perform an operation on
objafter 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:
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
objvariable 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:
and this:
…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.