【问题标题】:How to include reference to original function when doing an override with jQuery.extend() [closed]使用 jQuery.extend() 进行覆盖时如何包含对原始函数的引用 [关闭]
【发布时间】:2012-10-04 17:41:53
【问题描述】:

所以,我试图重写一个函数,但将它的原始方法包含在 jQuery.extend() 方法中。

    var origFunction = $.fn.pluginFunction;
    $.fn.extend({
        pluginFunction: function() {
               // `origFunction` is available via Closure, 
               // now how can I declare the $.extended function here
               // to preserve the original methods and then override
               // only the following object?

                   myObject = {
                        'key1' : 'val1',
                        'key2' : 'val2',
                   }
        }
    });

【问题讨论】:

    标签: javascript debugging syntax scope extend


    【解决方案1】:

    使用apply() 调用原件。

    origFunction.apply(this,arguments);
    

    但如果myObjectorigFunction 内部的局部变量,则不会有任何影响。

    【讨论】:

    • 这不起作用,因为执行origFunction.apply(this,arguments) 会过早地执行函数。我正在尝试调试它,并添加一个回调,以便我可以确保在执行之前正确扩展该函数,但是您建议的 origFunction() apply 实际上是我的问题的根源 - 在调试器中遍历它,它是在插件被扩展之前执行的这一行。
    • 它是如何过早执行的?不明白你的意思。
    【解决方案2】:

    修改代码:使用apply 调用origFunction。只有当它不是方法的私有变量时才更改 myObject(它应该可以从覆盖方法全局访问)。

    var origFunction = $.fn.pluginFunction;
        $.fn.extend({
            pluginFunction: function() {
                   origFunction.apply(this, arguments); // 
                   // `origFunction` is available via Closure, 
                   // now how can I declare the $.extended function here
                   // to preserve the original methods and then override
                   // only the following object?
    
                       myObject = {
                            'key1' : 'val1',
                            'key2' : 'val2',
                       }
            }
        });
    

    【讨论】:

    • 这不起作用,因为执行origFunction.apply(this,arguments) 会过早地执行函数。我正在尝试调试它,并添加一个回调,以便我可以确保在执行它之前正确扩展该函数,但是您建议的 origFunction() apply 实际上是我的问题的根源 - 在调试器中遍历它,它是在插件被扩展之前执行的这一行。
    【解决方案3】:

    用户申请()

    apply 调用带有一组参数的函数。它不是 jQuery 的一部分,而是核心 Javascript 的一部分。但是,在 jQuery 文档中有提到它:

    http://docs.jquery.com/Types#Context.2C_Call_and_Apply

    语法:

    somefunction.apply(thisobj, argsarray)
    

    上面调用了函数somefunction,将this设置为函数作用域内的thisobj,并将argsarray中的参数作为参数传递给函数。

    【讨论】:

      猜你喜欢
      • 2017-02-06
      • 2010-09-22
      • 2013-07-28
      • 2016-12-05
      • 1970-01-01
      • 2012-05-12
      • 1970-01-01
      • 2015-12-19
      相关资源
      最近更新 更多