【发布时间】:2026-01-12 13:30:01
【问题描述】:
有没有更简单的方法在没有匿名函数的原型方法上调用过滤器?
不知道有没有等价于myArray.filter(function(it){ it.method() })。
这看起来很接近可行的方法(它不可行):
function X() {}
X.prototype.method = function() { console.log(this); }
[new X(), new X()].filter(X.prototype.method.call);
相反,我在最新的 Firefox 和 Chrome 中都收到了 TypeError,这是因为它并没有完全符合我的要求:
x = function() { console.log(this) }
x.call(123) //logs 123
y = x.call //reports that y is of type function in console
y(123) //TypeError: Function.prototype.call called on incompatible undefined
y.call(x, 123); //this is what you really need
我试过用bind,可能是我漏掉了,但如果不是单行的话,也比不上匿名方法形式:
function X() {}
X.prototype.method = function() { console.log(this); }
y = X.prototype.method.call
y.bind(X.prototype.method)
[new X(), new X()].filter(y);
【问题讨论】:
-
.bind返回一个新函数,它不会修改函数本身。所以,y = y.bind(...)
标签: javascript