使用jQuery.extend覆盖函数的原因可能是什么?

时间:2016-09-28 15:03:59

标签: jquery twitter-bootstrap extend

我正在寻找一种扩展bootstrap插件的正确方法,并找到了这个答案:https://stackoverflow.com/a/12689534/1276032

让我感到困扰的是最后一节 - 初始化覆盖。复制代码如下:

// 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 - 它是否有一些我看不到的效果?如果我执行此代码:

var f1 = function(){console.log(1);};
var f2 = function(){console.log(2);};
var f2 = $.extend(f1,f2);
f2();

然后只有1打印到控制台,f1等于f2。所以这似乎很简单,但

$.fn.modal = function(option) {...}

但也许我想念一些......

1 个答案:

答案 0 :(得分:0)

你需要改变这个:

$.fn.modal = $.extend(function(option) {
    // your code ...
}, $.fn.modal);

为此:

$.extend($.fn.modal, function(option) {
    // your code ...
});

TL; DR

$.extend(a, b) a 修改其内容)上复制 b 的内容,如果有重复,则属性的 b 仍然存在。此外,它返回 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);相同:

$.extend(f1, f2) // Copy properties of f2 to f1
f2 = f1

来源:https://api.jquery.com/jquery.extend/

相关问题