为什么要将空对象传递给jQuery的extend方法? [英] Why pass an empty object to jQuery's extend method?

查看:102
本文介绍了为什么要将空对象传递给jQuery的extend方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

jQuery有一个非常简洁的 extend 方法,将2个对象合并为一个。

jQuery has a very neat extend method, which merges 2 objects into one.

jQuery插件创作页面他们显示如下示例:

var settings = $.extend({
    'location'         : 'top',
    'background-color' : 'blue'
}, options);

但是,我看到很多插件都将一个空对象作为第一个参数传递,如下所示: / p>

However, I've seen many plugins pass an empty object as the first parameter, like so:

var settings = $.extend({}, {
    'location'         : 'top',
    'background-color' : 'blue'
}, options);

据我所知,这两个完全相同。唯一的区别是如果默认值将存储在自己的变量中:

As far as I can tell, these two do the exact same thing. The only difference would be if the defaults would have been stored in its own variable:

var defaults = {
    'location'         : 'top',
    'background-color' : 'blue'
},
settings = $.extend({}, defaults, options);

这样,您可以随时访问默认值而不会被覆盖选项

This way, you can always access your defaults without them being overridden by the options.

以下是问题:为什么这么多插件作者选择将空对象传递给 extend ,即使它们没有将默认值存储在变量中?

Here's the question: Why do so many plugin authors opt to pass an empty object to extend, even when they don't store the defaults in a variable?

我错过了什么吗?

推荐答案

可能的原因(对于第二个例子) ...


  • 继承无知...... (看到它这样做,并复制了练习)

内在的无知...... (看到它在你的上一个代码块中正确完成,但用一个即时对象替换了缓存的对象并且不知道应该删除空对象)

Intrinsic ignorance... (saw it done properly as in your last code block, but replaced the cached object with an on-the-fly object and didn't know that the empty object should be removed)

全球变暖。

缺乏对细节的关注...... (类似于第2点,知道没有必要,但从未真正采取过我要检查代码)

Lack of attention to detail... (similar to point 2, knows it isn't necessary but never really took the time to examine the code)

全局冷却。

过度防御性编码...... (担心有一天默认值会被重写为可重用的对象,并担心当时不会插入空对象)

Overly defensive coding... (afraid that the defaults may someday be reworked into a reusable object, and is afraid that the empty object won't be inserted at that time)

jQuery开发人员总是做声音告诉他们的事情; - )

jQuery developers always do what the voices tell them ;-)

总体, 你是对的。创建中间对象,将其复制到空对象,然后丢弃。这是一种不必要和浪费的做法。

Overall, you're right. The middle object is created, copied to an empty object, then discarded. It's an unnecessary and wasteful practice.

这篇关于为什么要将空对象传递给jQuery的extend方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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