为什么 Closure 在使用 function.apply 时不对参数进行类型检查?
Why does not Closure type-check the parameters when using function.apply?
见下文
/**
* @param {string} a
* @param {string} b
*/
var f = function(a, b){
// ...
}
/**
* @param {string} a
* @param {boolean} c
*/
var h = function(a, c){
f.apply(this, arguments); // no compile error
f.apply(this, [a, c]); // no compile error
f.call(this, a, c); // compile error: does not match formal parameter
}
为什么 Closure 只在使用 call 而不是 apply 时引发错误?
有没有一种方法可以让我在使用 apply 时对参数进行闭包类型检查?
因为 (a) 类型检查器还没有元组类型的概念,并且 (b) 很少用数组字面量调用方法。使用 .call 时,确定将哪个参数分配给哪个参数槽是微不足道的。
如果类型系统生成元组类型,那么在检查 .apply 上投入更多精力是有意义的,因为数组 "slot" 类型和长度更有可能是已知的。
见下文
/**
* @param {string} a
* @param {string} b
*/
var f = function(a, b){
// ...
}
/**
* @param {string} a
* @param {boolean} c
*/
var h = function(a, c){
f.apply(this, arguments); // no compile error
f.apply(this, [a, c]); // no compile error
f.call(this, a, c); // compile error: does not match formal parameter
}
为什么 Closure 只在使用 call 而不是 apply 时引发错误?
有没有一种方法可以让我在使用 apply 时对参数进行闭包类型检查?
因为 (a) 类型检查器还没有元组类型的概念,并且 (b) 很少用数组字面量调用方法。使用 .call 时,确定将哪个参数分配给哪个参数槽是微不足道的。
如果类型系统生成元组类型,那么在检查 .apply 上投入更多精力是有意义的,因为数组 "slot" 类型和长度更有可能是已知的。