如何将原先传递给原型函数的参数的引用传递给同样传递给相同原型函数的回调函数?
实现的目的是通过执行回调函数来循环获得原型的值。
Number.prototype.loop = function(index, callback) {
return Array(this).fill(0).forEach((e, i) => {
if(callback)
callback();
});
};
var num = 3;
num.loop(index, function(){
console.log(index);
});
解决方案显然,应该将对index
的引用直接传递给回调函数,以指示原型函数中Array的实际索引属性将传递给回调函数。
Number.prototype.loop = function(callback) {
return Array(this).fill(0).forEach((e, i) => {
if(callback)
callback(i);
});
};
var num = 3;
num.loop((index) => {
console.log(index);
});
有两个错误。
将索引i
传递给callback
函数中的Number.prototype.loop
,而不是调用方:
num.loop(index, function(index) {
→num.loop(function(index) {
Number.prototype.loop = function(index, callback) {
→Number.prototype.loop = function(callback) {
callback();
→callback(i);
将this
的数值而不是实例本身传递给Array
构造函数:
Array(this)
→Array(this.valueOf())
Number.prototype.loop = function(callback) {
var num = this.valueOf();
return Array(num).fill(0).forEach((e, i) => {
if (callback)
callback(i);
});
};
var num = 3;
num.loop(function(index) {
console.log(index);
});
您可以使用以下函数Number
扩展loop
本机类。但是,建议不要按照此eslint's rule
扩展本机。
eslint's rule