使用jQuery.extend覆盖函数的原因可能是什么? [英] What might be a reason of overriding function using jQuery.extend?
问题描述
我在寻找扩展Bootstrap插件的正确方法,并找到了以下答案: https://stackoverflow.com/a/12689534/1276032
I was searching for a proper way of extending bootstrap plugin, and found this answer: https://stackoverflow.com/a/12689534/1276032
困扰我的是最后一部分-初始化覆盖.复制的代码如下:
What troubles me, is the last section - initialization overriding. Copied code below:
// override the old initialization with the new constructor
$.fn.modal = $.extend(function(option) {
var args = $.makeArray(arguments),
option = args.shift();
return this.each(function() {
var $this = $(this);
var data = $this.data('modal'),
options = $.extend({}, _super.defaults, $this.data(), typeof option == 'object' && option);
if ( !data ) {
$this.data('modal', (data = new Modal(this, options)));
}
if (typeof option == 'string') {
data[option].apply( data, args );
}
else if ( options.show ) {
data.show.apply( data, args );
}
});
}, $.fn.modal);
我不明白为什么在这种情况下使用$ .extend -它会产生一些我看不到的效果吗?如果我执行以下代码:
I don't understand why $.extend is used in this case - does it have some effect that I don't see? If I execute this code:
var f1 = function(){console.log(1);};
var f2 = function(){console.log(2);};
var f2 = $.extend(f1,f2);
f2();
然后只有1打印到控制台,并且f1等于f2.这样看来,简单的拼命就可以了,
then only 1 is printed to the console, and f1 equals f2. So it seems simple assingnment would do,
$.fn.modal = function(option) {...}
但是也许我想念一些东西...
but maybe I miss something...
推荐答案
您需要更改此设置:
$.fn.modal = $.extend(function(option) {
// your code ...
}, $.fn.modal);
为此:
$.extend($.fn.modal, function(option) {
// your code ...
});
TL; DR
$.extend(a, b)
将 b 的内容复制到 a (修改其内容)上,如果重复,则 b 仍然存在.同样,它返回 a 的值.
$.extend(a, b)
copies the content of b on a (modifying it's content), and if any repeated, then the property of b remains. Also, it returns the value of a.
所以,如果您有这个:
hello = { unique_on_hello: 'hola', message: 'hello message' }
world = { unique_on_world: 'mundo', message: 'WORLD MESSAGE' }
response = $.extend(hello, world)
每个值将为:
hello // {unique_on_hello: "hola", message: "WORLD MESSAGE", unique_on_world: "mundo"}
world // {unique_on_world: "mundo", message: "WORLD MESSAGE"}
response // {unique_on_hello: "hola", message: "WORLD MESSAGE", unique_on_world: "mundo"}
因此,如果您执行 f2 = $.extend(f1,f2);
与相同:
So, if you do f2 = $.extend(f1,f2);
is the same as:
$.extend(f1, f2) // Copy properties of f2 to f1
f2 = f1
来源: https://api.jquery.com/jquery.extend/
这篇关于使用jQuery.extend覆盖函数的原因可能是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!