我正在尝试将此函数从原型(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/