使用回调参数

Using callback arguments

我有一个自定义 jQuery 函数,它获取输入选项对象,并在完成后向 运行 回调函数。此外,在 jQuery 函数内,我创建了一个回调对象,其中包含我希望在回调函数中可用的函数。

keyboardInput : function(input, callback){
    // ...
    if(typeof callback === 'function') {
        callback.call(self.callback);
    }
    // ...
    self.callback = {
        hideCursor : function(){self.hiddenCursor = true;},
        showCursor : function(){self.hiddenCursor = false;},
    }
}

所以我调用了我的 jQuery 函数和回调 运行s,但是我没有 self.callback 对象在里面。

$('.txt-fx.keyboard-input.first').keyboardInput({
    speed : [60, 120],
    cursor : 'box',
    cursorBorderWidth : 3,
    delay : 2000,
}, function(obj){
    setTimeout(function(){
        obj.hideCursor();
        $('.txt-fx.keyboard-input.second').keyboardInput({
            speed : [60, 120],
            cursor : 'box',
            cursorBorderWidth : 3,
           delay : 2000,
        });
    }, 3000)
});

抛出:

Uncaught TypeError: Cannot read property 'hideCursor' of undefined

我做错了什么?

.call 的语法是 fn.call(thisarg, parameter1, parameter1 ...)

您正在将回调的 this 设置为 self.callback - 请参阅 MDN Documentation of function.call

你可能想做的事:

callback.call(null, self.callback);