首页 > 解决方案 > 实现 Number.prototype.loop(callback)

问题描述

如何将最初传递给原型函数的参数引用传递给回调函数,回调函数也传递给相同的原型函数?

实现的目标是Number通过执行回调函数来循环获取 的值。

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);
});

标签: javascriptprototype

解决方案


有2个错误。

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


推荐阅读