问题描述
在中,有以下示例:
函数negate(func){
返回函数(x){
return!func(x);
};
}
var isNotNaN = negate(isNaN);
警报(isNotNaN(NaN));
只知道基本的Javascript和命令式编程,我被这种编程风格所困扰。有人可以帮助我理解运行时会发生什么。
我浏览了代码并检查了变量,发现 x
是 NaN
。它如何知道 isNaN
的参数应该作为参数 x
传递给匿名函数?首先,为什么的实际参数NaN isNotNaN
变成了 isNaN
的参数(即 isNaN
需要一个参数,为什么它会从 isNotNaN
)的参数中使用它?
理解这种情况的最佳方式可能是看看这些东西实际上是否相等。请注意 func
如何成为传递的 isNaN
函数。
函数negate(func){
返回函数(x){
return!func(x) ;
};
}
var isNotNaN = negate(isNaN);
/ *
isNotNaN = function(x){
return!isNaN(x)
}
* /
警报(isNotNaN(NaN));
In http://eloquentjavascript.net/1st_edition/chapter6.html, there is the following example:
function negate(func) {
return function(x) {
return !func(x);
};
}
var isNotNaN = negate(isNaN);
alert(isNotNaN(NaN));
Knowing only basic Javascript and imperative programming, I am stumped by this programming style. Can someone help me to understand what happens during runtime.
I stepped through the code and inspected variables and found that the value of x
is NaN
. How does it know that the argument to isNaN
should be passed as argument x
of the anonymous function? In the first place, why does the actual parameter NaN of isNotNaN
become the argument to isNaN
(ie while isNaN
expects an argument, why does it take it from the argument of isNotNaN
)?
Best way to understand this might be with seeing what these things actually equal. Notice how func
becomes the passed isNaN
function.
function negate(func) {
return function(x) {
return !func(x);
};
}
var isNotNaN = negate(isNaN);
/*
isNotNaN = function(x){
return !isNaN(x)
}
*/
alert(isNotNaN(NaN));
这篇关于在Javascript中传递函数时如何处理参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!