我正在阅读John Resig的“Javascript忍者的秘密”,并尝试了其中一个关于currying和parital函数的例子。代码如下:
<html>
<body>
<button id="test">Click Me!</button>
</body>
<script type="text/javascript">
Function.prototype.curry = function() {
var fn = this,
args = Array.prototype.slice.call(arguments);
return function() {
return fn.apply(this, args.concat(
Array.prototype.slice.call(arguments)));
};
};
var elem = document.getElementById("test");
var bindClick = elem.addEventListener.curry("click");
bindClick(function(){ console.log("OK"); });
</script>
</html>然而,下面的代码似乎生成了一个错误,未捕获TypeError: apply函数上的非法调用。
我似乎找不出原因,因为这一切似乎都是有意义的。bindClick将返回一个匿名函数,该函数使用window作为函数上下文(this)调用函数elem.addEventListener,参数将为["click", function() {console.log("OK"); }]
发布于 2013-03-22 17:20:08
问题是您丢失了元素的上下文。必须在元素上调用addEventListener方法,但在函数上调用它:
// Here, `this` refers to a function, not an element
return fn.apply(this, args.concat(Array.prototype.slice.call(arguments)));您需要将元素传递给您的新函数。例如:
Function.prototype.curry = function () {
var fn = this,
args = Array.prototype.slice.call(arguments);
return function (context) {
return fn.apply(
context,
args.concat(Array.prototype.slice.call(arguments, 1))
);
};
};这是一个working example。请注意,在返回的函数中添加了一个context参数,还要注意在slice调用中添加了第二个参数-删除新的context参数并仅应用以下参数时需要使用该参数。
https://stackoverflow.com/questions/15566519
复制相似问题