`var options = options ||之间的区别{}`和`选项|| (options = {})` [英] Difference between `var options = options || {}` and `options || (options = {})`

查看:184
本文介绍了`var options = options ||之间的区别{}`和`选项|| (options = {})`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常使用 var options = options || {} 作为默认为空对象的方法。它通常用于初始化一个选项对象,以防它未在函数调用的参数中传递。

I often use var options = options || {} as way to default to an empty object. It's often used to initialize an option object in case it's not passed in the parameter of a function call.

我在几个地方读过的东西(博客帖子,源代码)选项|| (options = {})更好地表达开发人员的意图。有人可以详细说明吗?我没有看到两者之间的功能差异,所以我必须在这里找到一些东西。

The thing is I've read in several places (blog posts, source code) that options || (options = {}) better express the developer's intent. Can someone elaborate on it? I don't see the functional difference between the two, so there's something I must be missing here.

---编辑

我在几个地方的Backbone.js源代码中看到过,比如 https://github.com/documentcloud/backbone/blob/0.9.2/backbone.js#L273

I saw in Backbone.js source code in several places, like https://github.com/documentcloud/backbone/blob/0.9.2/backbone.js#L273

我想我看到了它在jQuery的源代码中也是如此。并且在多个Js写作风格指南中蓬勃发展。

I think I saw it too in jQuery's source code too. And in the multiple Js writing style guides that flourished.

---编辑2代码示例:

--- edit 2 code example :

var func = function(param, options) {
   // How I do it
   var options = options || {};
   // How I should do it in the "same" way
   options = options || {};
   // The "other" way
   options || (options = {});

}


推荐答案

他们应该做同样的事情,但有一个更好的方法。

They should do the same thing, but there is a better way.

理论上第二个,仅在值为假的情况下进行分配,可以消除分配并加快速度。实际上在jsperf中我们看到它是(12%)。

Theoretically the second, assigning only if the value is falsy, could eliminate an assignment and be faster. Indeed in a jsperf we see it is (12%).

事实上,显式if语句与条件然后分配一样快:

In fact the explicit if statement is just as fast as the condition-then-assign:

if(!options)
    options = {};

在您的浏览器/计算机上尝试测试

我认为明确的if是最明确的,并且没有惩罚。

I think the explicit if is the most clear, and has no penalty.

编辑:

如果您希望将对象传入函数,那么我认为更好的测试是:

If you are expecting an object to be passed in to a function, then I think the better test is:

if(typeof options !== 'object') 
    options = {};

这将确保您之后有一个对象,即使它是空的。任何其他测试(对于未定义或虚假)将允许真正的非对象通过非零数字或非空字符串。然而,正如jsperf所示,这慢了约15%。由于你只是在进入一个处理对象的函数时这样做,我认为这是一个值得的权衡,并且总是分配的速度慢得多。

This will ensure that you have an object afterwards, even if it is empty. Any other test (for undefined, or falsiness) will permit a truthy non-object through like a non-zero number or a non-empty string. As the jsperf shows, however, this is ~15% slower. Since you only do this on entry to a function which will be processing objects, I would argue that is a worthwhile tradeoff, and is barely slower that the always-assign.

这篇关于`var options = options ||之间的区别{}`和`选项|| (options = {})`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆