javascript - typescript 绑定(bind)问题

标签 javascript jquery prototype typescript

我正在尝试将此函数从原型(prototype)移植到 typescript 中的 jquery:

    onFailure: function(xhr) {
    // Get options
    var opts = this;

    // Show result
    var msgBox = opts.msgBox ? opts.msgBox : opts.client.options.msgBox;  
    if (msgBox && !opts.onFailure) {
        msgBox.showError('Communicatie fout.');
    }

    // Handle onFailure callback
    if (opts.onFailure) {
        opts.onFailure.bind(opts.client)(xhr);
    }
    else if (opts.options && opts.options.onFailure) {
        opts.options.onFailure.bind(opts.client)(xhr);
    }

    // Fire event
    opts.client.failureCb.fire('failure');
},

这是移植的代码:

        onFailure(xhr){
            // Get options
            var opts = this;

            // Show result
            var msgBox = opts.msgBox ? opts.msgBox : opts.client.options.msgBox;
            if (msgBox && !opts.onFailure) {
                msgBox.showError('Communicatie fout.');
            }

            // Handle onFailure callback
            if (opts.onFailure) {
                opts.onFailure(opts.client)(xhr);
            }
            else if (opts.options && opts.options.onFailure) {
                opts.options.onFailure.bind(opts.client)(xhr);
            }

            // Fire event
            opts.client.failureCb.fire('failure');
        }

如您所见,两者并无太大区别。然而,问题来自 typescript 编译器:

error TS2094: The property 'bind' does not exist on value of type 'null'

这应该如何正确移植到 jquery?

谢谢。

最佳答案

发生这种情况的唯一原因是 typescript 已根据您所写的内容推断出类型:

var opts = {
    options:{
        onFailure: null
    }
} 

// The property 'bind' does not exist on value of type 'null'
opts.options.onFailure.bind(); 

您可以通过显式键入变量为 any 来覆盖此行为:

var opts:any = {
    options:{
        onFailure: null
    }
} 

// no more error
opts.options.onFailure.bind(); 

这将消除编译错误,但我怀疑此编译错误可能指向代码中的有效逻辑错误。

关于javascript - typescript 绑定(bind)问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19702511/

相关文章:

Javascript 分配原型(prototype)困惑

javascript - 我的页面上注册了哪些事件?

javascript - JavaScript 中的 "\"字符有什么问题?

javascript - 尝试通过单击另一个页面上的链接访问页面上的部分时出错

javascript - 实例化是如何工作的?

javascript - Javascript 中未定义函数的奇怪错误

javascript - AngularJS HTTP 使用响应

javascript - 在 Canvas 中动画绘制对象

jquery - 基于容器大小的响应字体大小

javascript - javascript中的跨浏览器水平和垂直滚动事件