Javascript 如何使用新对象扩展$.fn

Javascript 如何使用新对象扩展$.fn,javascript,jquery,Javascript,Jquery,我有以下jquery函数: (function($) { $.fn.formCheck = function(options) { var form = this; var errorList = []; var settings = { errorClass: "error", focusInvalid: true, errorContainer: $([])

我有以下jquery函数:

(function($) {
    $.fn.formCheck = function(options) {
        var form = this;  var errorList = [];
        var settings = {
             errorClass: "error",
             focusInvalid: true,
             errorContainer: $([])
        }

        // Extend the options so they work with the plugin
        if(options) {
            $.extend(settings, options);
        }

         var fc = {
              messages: {
                required: "Dieses Feld ist ein Pflichtfeld.",
                remote: "Please fix this field.",
                email: "Geben Sie bitte eine gültige E-Mail Adresse ein.",
             }
          }
    }
})(jQuery);
现在,我想用以下代码扩展它们:

(function($) {
    $.extend(formCheck.fc.messages, {
          required: "This field is required.",
          remote: "Please fix this field.",
          email: "Please enter a valid email address.",
    });
}(jQuery));
我收到消息ReferenceError:formCheck未定义

怎么了


我制作了一个新的JSFIDLE:

您需要全球化您的选项(通过插件使任何附加配置都可以访问它)。例如:

(function($){
    $.fn.coloredTextOptions = {
        color: 'blue'
    };
    $.fn.coloredText = function(options){
        var opts = $.extend({}, $.fn.coloredTextOptions, options);
        return this.css('color', opts.color);
    };
})(jQuery);

$('p').coloredText(); // text is blue (as was set initially)

(function($){
    $.extend($.fn.coloredTextOptions, {
        color: 'red'
    });
})(jQuery);

$('p').coloredText(); // text is red (as modified by extend)

$('p').coloredText({ color: 'green' }); // text is green
                                        // (as overridden by passed options)

您已经扩展了jQuery的
fn
属性,以包括
formCheck
函数。但在下面,你正试图像这样访问它

formCheck.fc.messages
函数
formCheck
存在于jQuery对象中名为
fn
的属性中。您必须像这样访问它
$.fn.formCheck
$.fn['formCheck']

第二,假设您决定这样声明函数

   (function () {
       var formCheck = function () {
           // Code
       }
   })();

   formCheck(); // ReferenceError. Not defined
因为您已经将它包装在匿名函数中,所以在该范围之外它是不可见的。您需要将其暴露到更高级别的范围中,以使上述功能正常工作

   (function () {
       var formCheck = function () {
           // Code
       }

       window.formCheck = formCheck;
   })();

   formCheck(); // This works. Equivalent to calling `window.formCheck();`
另一个错误是试图访问函数的私有变量
fc
,就好像它是一个属性一样。
我建议你阅读这篇文章

你不能从外部访问
fc
。它只存在于匿名函数中。调用插件时,应将选项传递给插件,并在插件代码中使用
$.extend
。您可以使用
$.extend(设置、选项)执行此操作
,因此对
消息执行相同的操作
fc
是一个私有变量。它不是
formCheck
函数的属性,因此不能像
formCheck.fc
这样访问它。如果您看到类似于我的内容,请告诉我在这里不会做什么:对不起,我不明白。我做了另一个jsfiddle:或者我现在做了,我不能访问fc。我把信息提高了一个层次。但它仍然不起作用。请看