我是否需要在 JQuery Widget 中每个函数的开头定义“self”、“元素”等

Do I need to define 'self', 'element' etc. at the start of every function within a JQuery Widget

本文关键字:定义 开头 self 函数 元素 是否 JQuery Widget      更新时间:2023-09-26

我创建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>

最终总是不得不在我创建的每个函数中声明selfoptionselement

我是否

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

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

当您在 jQuery 函数中使用回调时,self 变量很有用,其中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>
还有一个问题也

通过在此处的对象文字中使用函数来触及这一点,但考虑到您最初的问题,这似乎过于冗长。