简体   繁体   English

jQuery插件结构:在插件定义内部访问JavaScript类?

[英]jQuery Plugin structure: Accessing JavaScript class inside plugin definition?

I have a question regarding the structure of a jQuery plugin that I found. 我对发现的jQuery插件的结构有疑问。

For better understanding, here is a simplified example of the plugins structure: 为了更好地理解,这是插件结构的简化示例:

// 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();

For the most part, I get what is happening. 在大多数情况下,我了解正在发生的事情。 The actual plugin logic seems to be written as a normal JavaScript "class". 实际的插件逻辑似乎写为普通的JavaScript“类”。
This is followed by a jQuery plugin definition – I think, actually, some new method is added to jQuery's prototype. 接下来是jQuery插件定义–我认为,实际上,是在jQuery的原型中添加了一些新方法。 This is where things get tricky to me: 这是让我棘手的地方:

How is is possible to access the class instance inside the plugin, although the class is instantiated after the plugin definition? 尽管在插件定义之后实例化了类,但如何访问插件内部的类实例呢? Is there a mechanism at work similar to variable hoisting? 是否有一种类似于可变提升的工作机制?

In case you want to try something, here is a Fiddle of the example: http://jsfiddle.net/kq8ykkga/ 如果您想尝试一下,这里是示例的小提琴: http : //jsfiddle.net/kq8ykkga/

$(this).html($.myplug.getValue()); isn't evaluated until you call $('selector').myplug() , executing the function body. 直到您调用$('selector').myplug()来执行函数体时,才会对其进行评估

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM