【问题标题】:Is there a way to strip out a prototype method and make it work as a function?有没有办法剥离原型方法并使其作为函数工作?
【发布时间】:2019-04-11 14:36:33
【问题描述】:

有没有办法让 Array.prototype.map 成为一个函数并将其称为customMap(passitanyarray,function)

一般来说, 有没有办法让Array.prototype.(whatever) 拿走任何东西,让它成为你自己的功能。 例如喜欢 Array.prototype.map(function())

提取地图并像这样使用map([],function()) 而不是Array.prototype.map(function())

如果不清楚,我会解释更多。

谢谢, 提前

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#Polyfill

【问题讨论】:

  • [].map.call([], function () { ... }); 应该可以解决问题。而第二个 [] 是您的数组。

标签: javascript


【解决方案1】:

您可以像这样包装arr.map() 调用:

function map(arr, fn) {
  return arr.map(fn);
}

console.log(map([1,2,3], x => x + 1));

【讨论】:

  • Polyfill 我不能让它接受一个数组吗?
  • @JS Lover,如果没有定义,polyfill 只是简单地定义了the Array.prototype.map() 函数,所以这段代码仍然可以工作,因为它会在这种情况下调用这个特定的实现。
  • 我的意思是我不能修改那个代码并让它接受一个函数。而不是将其附加到原型上。
  • @JS 爱好者,我不明白,Array.prototype.map 已经在取一个函数了。 polyfill 也不接受函数,如果没有定义,它只是实现 Array.prototype.map
  • 是的,它没有。你是对的。我正在寻找一种修改它的方法,因为这是我在写问题时想要做的。但你的答案有效。谢谢。
【解决方案2】:

如果您愿意使用函数管理this 的正确上下文,您可以提取call() 函数并为其提供正确的上下文。这有点难看(我不确定它是否明智),但它可以工作并且即使使用 polyfill 也应该可以工作:

let arr = [1, 2, 3]

/* get reference to properly bound call() */
let map = Function.call.bind(Array.prototype.map)

/* now you can use it like a regular function */
let double = map(arr, item => item * 2)
console.log(double)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-13
    • 2016-05-26
    • 1970-01-01
    • 1970-01-01
    • 2011-04-07
    相关资源
    最近更新 更多