代码之家  ›  专栏  ›  技术社区  ›  Coder

来自不同文件的jQuery插件函数重写

  •  -2
  • Coder  · 技术社区  · 12 年前

    我想重写JS库中的函数。我有以下代码结构

    插件.js

    function Plugin(elements, options) {
        'use strict';
        return this.init(elements, options);
    }
    
    if (typeof module === 'object') {
        module.exports = Plugin;
    }
    
    (function (window, document) {
        'use strict';       
    
        Plugin.prototype = {
            defaults: {
                showFlag: false,
                indent: true                         
            },
    
            insertDiv: function(parentElement){
               //some jquery code;
            },
    
            insertCustomData: function(parentElement){
               //some jquery code
               this.insertDiv(parentElement);
            },
    
    
        };
    
    }(window, document));
    

    测试.html

    <html>
    <body>
      <div id="test"> 
        <p>Test Content</p>
      </div>
    </body>
    <script src="plugin.js"/>
    <script type="text/javascript">    
        var plugin = new Plugin('test', {showFlag: true, indent:false});                    
    </script>
    </html>
    

    我想重写plugin.js中的insertDiv()函数,并在我的test.html中提供我自己的insertDiv()实现

    因此,当我从insertCustomData()调用insertDiv()时,它应该在我的test.html中而不是在plugin.js中执行函数

    我有没有办法做到这一点?

    提前感谢。

    1 回复  |  直到 12 年前
        1
  •  1
  •   adeneo    12 年前

    当然,只是覆盖它

    <html>
    <body>
      <div id="test"> 
        <p>Test Content</p>
      </div>
    </body>
    <script src="plugin.js"/>
    <script type="text/javascript">    
    
        Plugin.prototype.insertDiv = function() {
            // something else ?
        }
    
        var plugin = new Plugin('test', {showFlag: true, indent:false});                    
    </script>
    </html>
    

    FIDDLE