javascript - 实现 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);
});
解决方案
有2个错误。
将索引传递
i
给callback
inNumber.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);
});
推荐阅读
- php - 使用 POST 参数从终端执行 php 文件
- javascript - 创建简单随机数时出错
- java - 在对 EventSourcingHandlers 的调用之间,实体的状态如何保持?
- ember.js - Ember.JS 当我创建一个新记录时,它如何排序
- python - 使用 Python 更改 HTML 中下拉菜单的值
- javascript - 如何获取 Float64Array 的长度作为值?
- javascript - 如何仅获取对象的名称并将其动态转换为字符串?
- xcode - 将 UIImage 从 UITableViewCell 传递到下一个 ViewController
- python - 熊猫清理
- apache-kafka - Kafks consumer.poll 不返回任何数据