实例检查附加到数据属性的 jQuery 插件实例

instanceof check for jQuery plugin instances attached to data attribute

本文关键字:实例 jQuery 插件 数据属性 检查      更新时间:2023-09-26

我创建了一个jQuery插件,它在内部使用类实例化,大致如下:

;(function ($, window, document, undefined) {
  'use strict';
  function MyPlugin(element, options) {
    this.settings = $.extend({}, options);
    this.$el = $(element);
    this.init();
    return this;
  }
  MyPlugin.prototype = {
    init: function(){},
    method1: function(){},
    method2: function(){}
  }
  $.fn.myplugin = function (options, val) {
        return this.each(function () {
            if(typeof options === 'object'){
                if (undefined == $(this).data('myplugin')) {
                    var plugin = new MyPlugin(this, options);
                    $(this).data('myplugin', plugin);
                }
            }
        });
    }
})(jQuery, window, document);

现在,从外部JavaScript代码中,我想确定.data('myplugin')可用的对象是否是MyPlugin的实例。即使控制台在扩展三角形前面清楚地注销"MyPlugin",以下代码:

$(el).data('myplugin') instanceof MyPlugin

错误中断,声称未定义 MyPlugin。(很可能是因为原型已在封装中定义)

那么检查instanceof的正确方法是什么?

注释作为答案:您的 MyPlugin 函数被周围的匿名函数隐藏。给它一个名字,并将其视为命名空间。我不声称自己是原始Javascript对象的专家(因为我使用TypeScript来简化所有这些混乱):

JSFiddle: http://jsfiddle.net/TrueBlueAussie/o6s4yep4/3/

;var mynamespace = function ($, window, document, undefined) {
    'use strict';
    mynamespace.MyPlugin = function(element, options) {
        this.settings = $.extend({}, options);
        this.$el = $(element);
        this.init();
        return this;
    }
    mynamespace.MyPlugin.prototype = {
        init: function () {},
        method1: function () {},
        method2: function () {}
    }
    $.fn.myplugin = function (options, val) {
        return this.each(function () {
            if (typeof options === 'object') {
                if (undefined == $(this).data('myplugin')) {
                    var plugin = newmynamespace.MyPlugin(this, options);
                    $(this).data('myplugin', plugin);
                }
            }
        });
    }
};
mynamespace(jQuery, window, document);
var $el = $('#el');
$el.click(function () {
    $(el).myplugin();
    debugger;
    alert($(el).data('myplugin') instanceof mynamespace.MyPlugin);
});

注意:我不确定为什么当您单击元素时会导致 false,但这至少对您来说是一个很好的起点。

如果我做对了:

var MyPlugin;
;(function ($, window, document, undefined) {
  'use strict';
  MyPlugin = function(element, options) {
    this.settings = $.extend({}, options);
    this.$el = $(element);
    this.init();
    return this;
  }
 // rest of code goes here