这样的程序如何运作? [英] How does such a program operate?
问题描述
function greaterThan(n){
return function (m){ return m> N; };
}
var greaterThan10 = greaterThan( 10 );
console .log(greaterThan10( 11 ));
我的尝试:
我是猜测:
i)var greaterThan10指定na值10.
ii)调用greaterThan10(11)指定ma值11
如果是这种情况,n怎么没有被值11替换?
检查一下,同样的问题在堆栈中回答了流量 [ ^ ]
简单来说,
function greaterThan(outer){
function innerFunction(inner){
返回内部>外;
};
return innerFunction;
}
console .log(greaterThan( 10 )( 11 ));
greaterThan
是一个输入的函数并返回函数
(innerFunction - >接受输入,返回
abool
比较外部
和内部
参数的价值)
所以调用greaterThan(10),它将实例化外部值为10的函数,并返回可以如下调用的innerFunction对象。由于函数
是返回,外部变量值(10)的生命周期将出现在内部函数中,直到窗口关闭。
通常,函数
由语法FunctionName(args,...)
调用
var outerFunction = greaterThan( 10 );
console.log(outerFunction( 11 ));
// 或
console.log(greaterThan( 10 )( 11 ));
了解有关函数和闭包的更多信息,请参阅:
JavaScript函数闭包 [ ^ ]
闭包 - JavaScript | MDN [ ^ ]
function greaterThan (n) {
return function (m) { return m > n; };
}
var greaterThan10 = greaterThan (10);
console .log( greaterThan10 (11) );
What I have tried:
i'm guessing:
i) var greaterThan10 assigns n a value 10.
ii) calling greaterThan10 (11) assigns m a value 11
If this is the case, how comes n is not replaced by value 11?
check this, same question answered in stack over flow [^]
In simple way,
function greaterThan(outer) { function innerFunction(inner) { return inner > outer; }; return innerFunction; } console.log(greaterThan(10)(11));
greaterThan
is a function which takes an input and returns aFunction
(innerFunction -> which takes an input andreturns
abool
value by comparingouter
andinner
arguments )
so by calling greaterThan(10), it will instantiate the function with outer value as 10 and it returns the innerFunction object which can be invoked as below. Since aFunction
is returned, the life time of the outer variable value (10) will be present in the inner function till the window is closed.
normally,Function
is called by the syntaxFunctionName(args,...)
var outerFunction = greaterThan(10); console.log(outerFunction(11)); // or console.log(greaterThan(10)(11));
to know more about function and closures refer :
JavaScript Function Closures[^]
Closures - JavaScript | MDN[^]
这篇关于这样的程序如何运作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!