Javascript评估问题 [英] Javascript Evaluation Questions
问题描述
var x = 5;
function f(y){ return (x+y)-2 };
function g(h){ var x = 7; return h(x) };
{ var x=10; z=g(f) };
我正在课堂上的课本中解决一些问题,为下一次考试做准备,无法弄清楚上面的评估方式。
I'm working through some problems from my textbook in my class to prepare for our next exam, and can't figure out how the above evaluates.
大多数情况下,我不理解调用z = g(f),因为当评估f时,它没有提供参数,所以它如何评估什么?它是如何知道y是什么?
Mostly, I don't understand the call z=g(f), as when f is evaluated, it isn't provided an argument, so how does it evaluate at all? How does it know what y is?
另外,就范围而言,我认为javascript将大多数事物视为全局变量,因此设置的最后一个x将是函数f中使用的x值,正确吗?
Also, as far as scoping goes, I believe javascript treats most everything as global variables, so the last x that is set would be the x value used in function f, correct?
感谢您的帮助!
请注意,这些是我正在练习准备考试的书后面的额外问题,这些不是直接的作业问题。
推荐答案
var x = 5;
function f(y){ return (x+y)-2 };
function g(h){ var x = 7; return h(x) };
{ var x=10; z=g(f) };
这将全局x设置为5,然后(在任何函数调用之前)10。括号'创建一个新范围。
This sets the global x to 5, then (before any function calls) 10. The braces don't create a new scope.
您将 f
传递到 g
function(它变为形式参数 h
)。然后用 x == 7
调用( g
是一个有自己范围的函数,所以这个 x
影响全局。)
You pass f
into the g
function (it becomes formal parameter h
). That is then called with x == 7
(g
is a function with its own scope, so this x
shadows the global).
输入 f
, x
成为形式参数 y
; y
因此为7. (x + y) - 2
然后 10 + 7 - 2
。
Entering f
, x
becomes the formal parameter y
; y
is thus 7. (x + y) - 2
is then 10 + 7 - 2
.
这篇关于Javascript评估问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!