1.3 KiB
Scope binding.
In this experiment we are testing to see if we can determine what kind of binding Javascript uses. Our code has multiple variables and nested functions that will help demonstrate. There are 3 possible cases.
-
Shallow binding: In this case, the variable
xwould be shallowly bound. When the functionsub4callssub2(through thesubxargument), the value ofxin the scope ofsub4would be used. In this case, the output would be4, as that is the value ofxinsub4. -
Deep binding: With deep binding, when the function
sub4callssub2, it would use the value ofxfrom the scope in whichsub2was originally defined (i.e.,sub1). In this case, the output would be1, as that is the value ofxinsub1. -
Ad-hoc binding: In ad-hoc binding, the value of
xwould be determined based on specific rules or conditions. For example, a developer might choose to bindxbased on a particular condition or flag. The output would depend on the specific implementation and rule defined for ad-hoc binding.
In JavaScript, the binding behavior is closest to deep binding. When sub2 is called within sub4, it references the value of x from the scope where it was originally defined (i.e., sub1). Therefore, when running this code, the output is 1.
