2

我对编写 jquery 插件比较陌生,希望有人能解释为什么我在下面简化的 jsFiddle 中的代码没有按预期解析。通过阅读 API 和众多教程博客(大多数只是重复相同的示例),我不知道为什么代理不输出“正确”而不是“错误”。

http://jsfiddle.net/Sheepish666/hZUvx/

!function ($) {
    "use strict";
    var plugin = function (element, options){
        this.init("plugin", element, options);
    };

    plugin.prototype = {
        constructor: plugin,

        string : "correct",

        init : function(type, element, options){
            this.type = type;
            this.$element = $(element);
            this.options = this.getOptions(options);
        },
        getOptions: function (options) {
            options = $.extend({}, $.fn[this.type].defaults, options, this.$element.data());
            return options;
        },

        test : function(){
            this.options.callbackFn("no proxy"); 
            $.proxy(this.options.callbackFn("proxy"), this);
        }
    };

    //

    var instance = null;
    $.fn.plugin = function( option, arg1, arg2, arg3, arg4 ){
        if(instance === null){
            var options = typeof option == 'object' && option;
            instance = new plugin(options);
        }
        if (typeof option == 'string') instance[option](arg1, arg2, arg3, arg4);
        return instance;
    };

    $.fn.plugin.Constructor = plugin;

    $.fn.plugin.defaults = {
        string : "wrong",
        callbackFn : function(type){
            $("body").html($("body").html() + type + " = "+ this.string + "<br>");
        }
    };

}(window.jQuery);

$.fn.plugin().test();

非常感谢你:)

4

0 回答 0