我可以使用/访问jQuery插件定义之外的greet()方法

Any way I can use/access the greet() method outside the jQuery Plugin definition?

本文关键字:greet 方法 定义 可以使 访问 插件 jQuery 我可以      更新时间:2023-09-26
;(function($) {
  var Sanbox = {
    init: function(options, elem) {
      self = this;
      // combine default options and user passing
      self.options = $.extend( {}, $.fn.sanbox.options, options );
      console.log( this );          // an instance of Sanbox() object the caller
    },
    greet: function() {
      console.log( 'work' );
    }
  };
  // create your sanbox plugin
  $.fn.sanbox = function(options) {
    return this.each(function() {
      var sanbox = Object.create(Sanbox);
      sanbox.init(options, this);
    })
  }
  // plugin default options
  $.fn.sanbox.options = {
    name : 'byer',
    age : 24,
    address : 'Lorem ipsum dolor sit amet.'
  };
})(jQuery);
// use

我可以使用/访问jQuery插件定义之外的greet()方法吗?

在init()方法中,"this"指的是什么?

要在插件定义之外使用greet(),您需要将其公开为插件的公共函数。这个问题解释了你如何做到这一点:jQuery插件创建和面向公众的方法

在init()方法中,this是一个具有Sanbox原型的对象。您使用Object.create(sanbox)创建了这个对象。