jQuery插件结构:在插件定义中访问JavaScript类?
我有一个关于我发现的jQuery插件结构的问题 为了更好地理解,以下是插件结构的简化示例:jQuery插件结构:在插件定义中访问JavaScript类?,javascript,jquery,Javascript,Jquery,我有一个关于我发现的jQuery插件结构的问题 为了更好地理解,以下是插件结构的简化示例: // Regular constructor function function MyPlugin() { this.myValue = "My Value"; } // Methods on the prototype MyPlugin.prototype.showValue = function() { alert($.myplug.getValue()); } MyPlugin.
// Regular constructor function
function MyPlugin() {
this.myValue = "My Value";
}
// Methods on the prototype
MyPlugin.prototype.showValue = function() {
alert($.myplug.getValue());
}
MyPlugin.prototype.getValue = function() {
return this.myValue;
}
// jQuery plugin
$.fn.myplug = function() {
// Why is is possible to access $.myplug here although it's not created yet?
return this.each(function() {
$(this).html($.myplug.getValue());
});
};
// Create new MyPlug instance
$.myplug = new MyPlugin();
// Calling the jQuery plugin on a DOM element
$('div').myplug();
在很大程度上,我了解正在发生的事情。实际的插件逻辑似乎是作为一个普通的JavaScript“类”编写的。接下来是jQuery插件定义——我认为,实际上,jQuery的原型中添加了一些新方法。这就是事情变得棘手的地方: 尽管类是在插件定义之后实例化的,但是如何访问插件内部的类实例呢?是否有类似于可变起重的工作机制
如果您想尝试一些东西,这里有一些示例:
$(this.html($.myplug.getValue())在调用$('selector').myplug()
,执行函数体之前,不会进行计算。感谢您的帮助!