简体   繁体   English

Javascript模块-覆盖功能

[英]Javascript module - overriding functions

I have the following pattern for a jQuery based JS plugin: 对于基于jQuery的JS插件,我具有以下模式:

var myplugin = ( function ( $ )
{

    // (...)

    var myfunction = function()
    {
        console.log( "Calling default myfunction" );
    }

    // (...)

    return this;

})( jQuery );

I would like to enable third parties to override the functions (not necessarily any and all) within the plugin like so: 我想使第三方能够覆盖插件中的功能(不一定是所有功能),如下所示:

myplugin.myfunction = function()
{
    console.log( "Calling overridden myfunction" );
}

Can this be done without defining anything else in the global scope? 可以在不定义全局范围内任何其他内容的情况下完成此操作吗?

I realise that what I want to do may not be feasible using this design pattern. 我意识到,使用这种设计模式可能无法实现我想做的事情。 If this is the case what type of pattern should I be looking for? 如果是这种情况,我应该寻找哪种类型的图案?

Many thanks! 非常感谢!

you can do like this way 你可以这样

 var myplugin = ( function ( $ )
{

    // (...)

    this.myfunction = function()
    {
        console.log( "Calling default myfunction" );
    }


    // (...)

    return this;

})( jQuery );


myplugin.myfunction = function()
{
    console.log( "Calling overridden myfunction" );
}
myplugin.myfunction();

DEMO DEMO

As far as good practices go, you shouldn't encourage modification of your plugin. 就好的做法而言,您不应该鼓励您修改插件。 Instead, you may allow modified copies of your plugin. 相反,您可以允许修改插件的副本

var myPlugin = (function createModule($){
  var module = {};

  module.extend(stuff, function(changes){
    $.extend(createModule(), changes || {});
  });

  module.something = function(){
     return 1;
  }
  return module;
})(jQuery);

Now if we call myPlugin.something() we get 1 . 现在,如果调用myPlugin.something()我们将得到1

If the user does this: 如果用户这样做:

var altPlugin = myPlugin.extend({
   something: function(){
      return 2;
   }
});

altPlugin.something() // => 2
myPlugin.something() // => 1

This allows us to non destructively modify the behavior or myPlugin. 这使我们能够非破坏性地修改行为或myPlugin。 If the user decides it wants to just overwrite myPlugin that'll still work, this just provides a better alternative. 如果用户决定仅覆盖仍然可以使用的myPlugin ,则可以提供更好的选择。

Yes, but not how you want. 是的,但不是您想要的。 You can use || 您可以使用|| operator and then use some options to be passed. 运算符,然后使用一些options进行传递。

(function ($) {
    $.fn.myplugin = function (options) {
        // (...)
        var myfunction = options.overRide || function () {
            console.log("Calling default myfunction");
        }
        // (...)
        return this;
    }
})(jQuery);

Now, you can pass any function like: 现在,您可以传递任何函数,例如:

$('selector').myplugin({
    overRide: function () {
        console.log("Calling overridden function ");
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM