Javascript:实现Number.Prototype.Loop(回调)

问题描述 投票:0回答:2

如何将原先传递给原型函数的参数的引用传递给同样传递给相同原型函数的回调函数?

实现的目的是通过执行回调函数来循环获得原型的值。

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);
});
javascript prototype
2个回答
1
投票

有两个错误。

  1. 将索引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);
  2. 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);
});

0
投票

您可以使用以下函数Number扩展loop本机类。但是,建议不要按照此eslint's rule扩展本机。

eslint's rule
© www.soinside.com 2019 - 2024. All rights reserved.