Shallow & Deep Binding - What would this program print?

Ricky picture Ricky · Mar 21, 2013 · Viewed 28.4k times · Source

I'm not sure how to do this...

function f1()
{
    var x = 10;
    function f2(fx)
    {
        var x;
        x = 6;
        fx();
    };

    function f3()
    {
        print x;
    };

    f2(f3);
};

For each of the following two binding methods, what would the program print? A) Shallow Binding B) Deep Binding

Thanks for the help!

Answer

Mari Ganesh Kumar picture Mari Ganesh Kumar · Jul 29, 2015

Deep/shallow binding makes sense only when a procedure can be passed as an argument to a function.

  • Deep binding binds the environment at the time a procedure is passed as an argument.
  • Shallow binding binds the environment at the time a procedure is actually called.

Deep binding.

Here f3() gets the environment of f1() and prints the value of x as 10 which is local variable of f1().

Shallow binding.

f3() is called in f2() and hence gets the environment of f2() and prints the value of x as 6 which is local to f2()