我已经创建了一个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
的正确方法是什么?
答案 0 :(得分:0)
如果我做对了:
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
答案 1 :(得分:0)
评论作为答案:您的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 ,但这对您来说至少是一个很好的起点。