javascript - 如何引用原型(prototype)中定义的函数

标签 javascript jquery

我正在尝试向使用 jquery 库的网页添加一项功能,该库似乎没有任何文档。 (来源不明)我的问题主要是由于缺乏对 jquery 插件模型和/或 javascript 内部工作原理的理解。

<强>1。插件启动如下

jQuery('div.carousel').scrollGallery({
                mask: 'div.mask',
                slider: 'div.slideset',
                slides: 'div.slide', ............ });

<强>2。该插件在jquery中定义如下

;(function($){
        function ScrollGallery(options) {
                this.options = $.extend({
                        mask: 'div.mask', ...... }, options);
                this.init();

<强>3。在 Object.prototype 声明中,我看到定义了以下函数 numSlide

ScrollGallery.prototype = {
....................
numSlide: function(c) {
                        if(this.currentStep != c) {
                                this.currentStep = c;
                                this.switchSlide();
                        }
                },
.......... };

问题。

如何从外部引用 numSlide(int) 函数?

我尝试了以下方法,但没有成功。

myx = jQuery('div.carousel').scrollGallery({ // var myx was added in the global scope
myx.numSlide(1); //error undefined is not a function

我尝试在 myx = jQuery('div.carousel').scrollGallery({ 的末尾添加 return this; 但它仍然返回 jQuery 对象。

我也尝试过

jQuery.scrollGallery().numSlide(2); //error undefined is not a function
jQuery.scrollGallery.numSlide(2); //same error 

我需要添加灯泡

// jquery plugin
        $.fn.scrollGallery = function(opt){
                return this.each(function(){
                        $(this).data('ScrollGallery', new ScrollGallery($.extend(opt,{holder:this})));
                });
        };
}(jQuery));

答案(我认为)

看起来 ScrollGalary 对象存储在选择器的数据中。所以我相信我可以执行以下操作 jQuery('selector').data('ScrollGallery').numSlide(2);

无论如何,我决定发布此内容,以防将来有人遇到类似的轻信情况。

最佳答案

实现此目的的一种方法是首先启动 ScrollGallery 对象,然后使用它。

var test = new ScrollGallery();
test.numSlide();

如果你想扩展 jQuery 并使用该函数,你可以按如下方式分配它

$.fn.scrollGallery = new ScrollGallery();

并使用它

$("window").scrollGallery.numSlide();

关于javascript - 如何引用原型(prototype)中定义的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24772060/

相关文章:

javascript - 将数字添加到父窗口中的变量

javascript - 单击时隐藏下拉菜单

javascript - React Router v4 - 页面组合

javascript - Laravel 5.0 : Calculation using LaravelCollective and jQuery

javascript - .show() 导致可滚动 DIV 在 Firefox 中跳转到顶部

javascript - 使用右/左动画隐藏/显示动态生成的表格列

javascript - ES6 fetch 函数返回 undefined

jquery - 为什么人们称 jQuery$ 别名为 'factory' ?

javascript - jQuery 未捕获类型错误 : Cannot read property 'text' of null

javascript - 不使用全局对象进行过滤