Javascript 在下划线源中使用apply
我正在研究下划线的用法,我有一个关于它们在u.defer函数中apply用法的快速问题。特别是在u.delay中,我们对u对象使用apply,而在uu.delay中,我们对null使用apply。既然我们在两个函数中都不使用“this”,为什么我们不能使用null而不是uu中的uuu.defer呢Javascript 在下划线源中使用apply,javascript,underscore.js,Javascript,Underscore.js,我正在研究下划线的用法,我有一个关于它们在u.defer函数中apply用法的快速问题。特别是在u.delay中,我们对u对象使用apply,而在uu.delay中,我们对null使用apply。既然我们在两个函数中都不使用“this”,为什么我们不能使用null而不是uu中的uuu.defer呢 var slice = Array.prototype.slice; //Delays a function for the given number of milliseconds, and th
var slice = Array.prototype.slice;
//Delays a function for the given number of milliseconds, and then calls it with the arguments supplied.
_.delay = function(func, wait) {
var args = slice.call(arguments, 2);
return setTimeout(function(){
return func.apply(null, args);
}, wait);
};
//Defers a function, scheduling it to run after the current call stack has cleared.
_.defer = function(func) {
return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
};
在delay()
中,调用apply()
会导致执行用户提供的函数。没有明显的或记录在案的合同,本应在本职能范围内。将null
作为传递此
引用很有意义,因为它简化了最终用户的调试:错误将很容易调查
另一方面,在
defer()
中,apply()
用于调用另一个下划线API方法,这是众所周知的,由开发人员控制。使用下划线作为这个
通常是有意义的,这是整个库的一个常见规则-它直观、简短,并且在以后需要时提供了灵活性。“为什么我们不能使用null而不是uuu中的uuuuuuu。defer,因为我们在两个函数中都没有实际使用'this'?”,但是我想传递\uu
会使它对将来的更改更加健壮,以防在某个时候使用这个。也许直接联系开发者?谢谢,这很有道理