0

我创建了类似这样的 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, 。optionselement

是否有一些基本的理解我错过了,或者我真的必须一直这样做?

4

2 回答 2

1

您根本不必这样做,这只是为了更容易访问函数内部的内容。

当您在 jQuery 函数中使用回调时,该self变量很有用,其中this将设置为您正在操作的元素。例如:

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

变量oel只是减少打字。如果您有 variableself或未更改引用this,则可以直接从对象访问optionselement属性。

于 2013-11-07T17:30:57.853 回答
1

由于您使用的是对象文字,因此每次都需要声明这些内容。您可以将对象文字包装为函数调用并以这种方式实现您想要的。

<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>

还有一个问题也涉及到这个问题,也就是在这里使用对象文字中的函数,但考虑到你原来的问题,这似乎过于冗长。

于 2013-11-07T17:38:23.730 回答