0



我开始制作插件,但插件内部的变量范围有问题。我希望能够从插件内的任何地方访问我的选项,但不确定如何,var $opts 仅对该函数可见,而我的公共函数无法访问它。有谁知道我会怎么做?

在此先感谢,哦,如果有人注意到我制作插件的方式有任何错误,请毫不犹豫地提及它们:D

//@@@@ Start of myViewport Plugin @@@@\\
(function($) {

  $.fn.myViewport = function(options) {
    var $opts = $.extend({}, $.fn.myViewport.defaults, options);

    //Plugin Here
    return this.each(function() {           

        alert('Initialising Plugin!' + $opts.privateText + $opts.publicText);
        myPrivateFunction();
    });
  };

  // private functions
  function myPrivateFunction($opts) {
        alert($opts.privateText);
  };

  // public functions
  $.fn.myViewport.myPublicFunction = function() {
        alert($opts.publicText);
  };

  // plugin defaults
  $.fn.myViewport.defaults = {
    privateText: 'This is a text from the privateText defaults',
    publicText: 'This is a text from the publicText defaults'
  };

})(jQuery);
//@@@@ End of myViewport Plugin @@@@\\
4

1 回答 1

1

像这样 :

(function($) {

  $.fn.myViewport = function(options) {
    var o = $.extend(vp, $.fn.myViewport.defaults, options);

    //Plugin Here
    return this.each(function() {           

        alert('Initialising Plugin!' + o.privateText + o.publicText);
        myPrivateFunction();
    });
  };

  var vp = $.fn.myViewport;

  // private functions
  function myPrivateFunction() {
        alert(vp.privateText);
  };

  // public functions
  vp.myPublicFunction = function() {
        alert(vp.defaults.publicText);
  };

  // plugin defaults
  vp.defaults = {
    privateText: 'This is a text from the privateText defaults',
    publicText: 'This is a text from the publicText defaults'
  };

})(jQuery);

演示在这里

于 2012-11-11T04:28:33.700 回答