【问题标题】:What might be a reason of overriding function using jQuery.extend?使用 jQuery.extend 覆盖函数的原因可能是什么?
【发布时间】:2017-02-06 15:41:46
【问题描述】:

我正在寻找扩展引导插件的正确方法,并找到了这个答案: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。所以看起来很简单的assingnment就可以了,

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

但也许我错过了什么......

【问题讨论】:

    标签: jquery twitter-bootstrap extend


    【解决方案1】:

    你需要改变这个:

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

    为此:

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

    TL;DR

    $.extend(a, b)b的内容复制到a上(修改其内容),如果有重复,则的属性em>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/

    【讨论】:

    • 感谢您的回复。我知道 $.extend 如何为对象工作。我的问题的线索与一个案例有关,当函数作为其参数传递时。您的建议(将 f2 = $.extend(f1,f2) 更改为 $.extend(f2,f1))并没有真正回答我的问题,因为我不想改变任何东西 - 我只想了解,为什么这段代码是被接受的一部分,并且实际上非常赞成回答(目前有 32 个赞成票)。此外 - 更改此代码仍然不会扩展任何内容。结果始终是第一个参数的函数。
    猜你喜欢
    • 2013-02-16
    • 2021-09-01
    • 2012-01-01
    • 1970-01-01
    • 2020-09-09
    • 2018-10-31
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多