【问题标题】:Any way I can use/access the greet() method outside the jQuery Plugin definition?有什么方法可以在 jQuery 插件定义之外使用/访问 greet() 方法?
【发布时间】:2015-10-18 18:55:56
【问题描述】:
;(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' 指的是什么?

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    要在插件定义之外使用greet(),您需要将其公开为插件的公共函数。这个问题解释了如何实现它: jQuery plugin creation and public facing methods

    在 init() 方法 this 内部是一个对象,其原型为 Sanbox。您使用 Object.create(sanbox) 创建了此对象。

    【讨论】:

      猜你喜欢
      • 2016-09-17
      • 2023-03-20
      • 2012-04-25
      • 1970-01-01
      • 2012-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多