我创建了jQuery小部件类似的东西

<script type="text/javascript">
(function ($) {
        $.widget("cb.bacon", {
            _create: function() {
                var self = this,
                    o = self.options,
                    el = self.element;

                 // Some code

            },

            _bacon: function() {
                var self = this,
                    o = self.options,
                    el = self.element;

                 // Some code
            },

            _smokey: function() {
                var self = this,
                    o = self.options,
                    el = self.element;

                 // Some code
            } 
        });
    })(jQuery);                 
</script>

我总是不得不宣布 self, options, element 在我创建的每个功能中。

是否有一些基本的理解,我缺少或真正必须一直这样做?

有帮助吗?

解决方案

您根本不必这样做,这只是为了使访问功能内部的这些更容易。

self 当您在jQuery函数中使用回调时,变量很有用, this 将设置为您所采取的元素。例如:

$('.bacon').each(function(){ $(this).css('background', self.getBackground()); });

变量 oel 只能减少打字。如果您有变化 self, ,或参考 this 不变,您可以访问 optionselement 直接来自对象的属性。

其他提示

自从使用对象字体以来,您需要每次声明这些内容。您可以将对象字样作为函数调用,并以这种方式实现自己想要的东西。

<script type="text/javascript">
function makeTheBacon() {
    var self = this;
    var o = self.options;
    var el = self.element;

    self._create = function() {...};
    self._bacon = function() {...};
    self._smokey = function() {...};
    return self;
}

(function ($) {
    $.widget("cb.bacon", makeTheBacon());
})(jQuery);
</script>

还有一个问题,也通过在对象中使用函数来触及此问题 这里, ,但考虑到您的原始问题,这似乎太冗长了。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top