简体   繁体   English

JavaScript向对象添加方法

[英]JavaScript adding methods to objects

I'm trying to extend a jQuery object but having some difficulty doing so. 我正在尝试扩展jQuery对象,但这样做有些困难。

$(document).ready(function() {
    $('.single-item').slick({
        dots: true,
        infinite: false,
        speed: 500,
        customPaging: function(slider, i) {
            // Theres a lot of stuff in this, removed for brevity
        },
        progressBar: function(slider, i) {
            // Want to create this method
            // alert is not defined
            window.onload(window.alert("YES"));
        }
    });
    // slick is not defined
    console.log(typeof(slick));
});

I'm trying a lot of things such as using jQuery's "extend": 我正在尝试许多事情,例如使用jQuery的“扩展”:

var progressBar = function(slider, i) {
    window.onload(window.alert("YES"));
};
$.extend(slick, progressBar);
// Also tried '.slick-slider' in place of slick

Also tried implementing: 还尝试实现:

$.fn.progressBar = function(i) { 
    window.onload(alert(this.i))
};

$('.single-item').progressBar(i);

"customPaging" exists in the main js file, which I do not want to alter -- but rather extend additional methods to the object. “ customPaging”存在于主js文件中,我不想更改-而是将其他方法扩展到该对象。 It takes "slider" and "i" as parameters. 它以“ slider”和“ i”为参数。 Since it already exists in the main js file, it was easy enough to manipulate it. 由于它已经存在于主js文件中,因此对其进行操作很容易。

However, I want to create an entirely new method called "progressBar" that also has access to the object's "slider" and "i" variables. 但是,我想创建一个名为“ progressBar”的全新方法,该方法也可以访问对象的“ slider”和“ i”变量。

Can anyone help me understand what's going on and demonstrate how to create the method "progressBar" like I want? 谁能帮助我了解发生了什么并演示如何根据需要创建方法“ progressBar”?

Its not working because you adding method to configuration object of some plugin, not extending jquery element. 它不起作用,因为您将方法添加到某些插件的配置对象中,而不扩展jquery元素。 If you want to add new method to the plugin you will probably have to edit its code. 如果要向插件添加新方法,则可能必须编辑其代码。

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

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