开发者

JavaScript object definition conditionals - which is better?

开发者 https://www.devze.com 2023-01-06 11:03 出处:网络
I\'ve come across two different ways to define/name objects and functions in JavaScript that first check for the existence of the name before using it.The issue is,开发者_如何学运维 I don\'t know whic

I've come across two different ways to define/name objects and functions in JavaScript that first check for the existence of the name before using it. The issue is,开发者_如何学运维 I don't know which one is better (from speed and usability standpoints) and it's impossible to use the boolean operators in a Google search to figure it out.

The first one I see most often:

var myNewObject = myNewObject ? myNewObject : function () {
    // Code goes here.
};

The second one seems more concise, but I've only seen it one or two places, so I don't know if there's a standard or even a name for it:

var myNewObject = myNewObject || function() {
    // Code goes here.
};

Functionally, they both do the same thing and they both seem to work in every browser I can test in. My question is this - which is better and why? Also, while the first definition is essentially a single-line conditional ... what is the second one called?


I would choose the latter if only for the fact that you type myNewObject twice instead of thrice.

Also, while the first definition is essentially a single-line conditional ... what is the second one called?

Short-circuit evaluation


I would use the second example, which is described as (Minimum Eval). Its simpler and seems more readable.

It's just like getting an event from onClick method across multiple browsers.

element.onclick = function (evt) {
  evt = evt || window.event
}


The latter, it's similar to the null coalesce operator in c# ?? when used in that manner

see: Is there a "null coalescing" operator in JavaScript?


FWIW I see the second approach more often, and (for my part) I feel it's more clear, concise, and idiomatic.


Both methods work. But I think the most optimized version is to simply use a normal if test like:

if(!myNewObject)
   myNewObject = ...

Doing in any one of the method you suggest in your answer, it might involve an unnecessary reassignment every time the function/object is already defined. I mean if myNewObject is already defined, the JavaScript runtime would have to perform an unnecessary reassignment myNewObject = myNewObject (unless the runtime doesn't optimize it out).

On Mozilla website they suggest to use a simple if, view this.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号