Javascript:object [method]()无效或如何为普通的Javascript代码构建jQuery插件

the*_*dnp 5 javascript methods jquery

我需要帮助为我的一个vanilla JS脚本制作一个jQuery插件,是当前的jQuery插件,但下一个版本使用更多方法,我需要以某种方式解决它们.

目前我正在研究这个问题

(function($) {
    var t;  
    $.fn.KUTE = function( method, start, end, ops ) { // method can be Animate(), fromTo(), to(), stop(), start(), chain(), pause(), stop(), etc
        return this.each(function(){        
            if ( method === 'to' ) {                
                t = new KUTE[method]( this, null, end, ops );
            } else if ( method === 'fromTo' || method === 'Animate' ) {
                t = new KUTE[method]( this, start, end, ops );
            } 
            if ( t !== undefined && typeof t[method] === 'function' ) {
                console.log(t) // this shows proper object
                t[method]() // this doesn't work
            }   
        });
    };  
})(jQuery);     
Run Code Online (Sandbox Code Playgroud)

为什么t[method]()不起作用,我怎样才能使它工作?

更新:我在这里添加一些关于如何解决此代码的示例代码.基本上我构建了一个补间对象

var tween = $(div).KUTE('to', { left: tl }, { easing: easing, duration: 1000 } );
Run Code Online (Sandbox Code Playgroud)

然后我需要start()它,stop()它和其他方法.

$(tween).KUTE('start'); // this should basically be it.
Run Code Online (Sandbox Code Playgroud)

现在,我一直在阅读一些类似Javascript的东西call(),apply()而且我有点认为这可能是必须的,但是即使这样t[method].call(t) // where t is "this",也行不通.我希望我说得对,表明我的问题,如果有任何错误,请纠正我.

非常感谢.

the*_*dnp 6

我想我找到了原因,我上面的上一条评论解释了它,我做了一个不同的jQuery函数.

(function($) {
    $.fn.KUTE = function( method, start, end, ops ) { // method can be Animate(), fromTo(), to(), stop(), start(), chain(), pause() 
        var tws = [], i, l = this.length;

        for (i=0;i<l;i++){
            var mt = this[i][method];
            if ( typeof mt === 'function' ) {
                mt.apply(this[i]);
            }    
            if ( method === 'to' ) {
                tws.push( new KUTE[method]( this[i], start, end ) ); // here start is end and end is ops 
            } else if ( method === 'fromTo' || method === 'Animate' ) {
                tws.push( new KUTE[method]( this[i], start, end, ops ) ); 
            }           
        }
        return tws;
    };
})(jQuery); 
Run Code Online (Sandbox Code Playgroud)

接下来要做的是,如果this.length > 1做一个好的小FOR()而不是超级坏和丑jQuery.each().

问题已解决,请参阅我的codepen以获取示例.

更新:我也添加了FOR它,它按预期工作.我更新了上面的答案.