Reputation: 509
In JavaScript it is possible to return a function as the output of a function.
I can also ascribe a variable the value of a function like
alert1=alert;
What is going on behind the scenes. My best guess is that the section of code in memory where the function alert exists is pointed to by alert1 now as well. Is this the case or is the entire code of alert being copied to alert1 so that another function exists in memory now.
Upvotes: 1
Views: 992
Reputation: 14466
Yes. It's just a reference. This might be easier to illustrate using a plain object as an example (but it applies to functions as well, since those are also objects in JS).
var obj = {foo: 'bar'};
var ref = obj;
obj.foo = 'bing';
console.log(ref.foo); // 'bing'
So ref
just has a reference to obj
. It doesn't copy the object. When you make a change to obj
, it's reflected on ref
, because its value is just a reference to obj
.
Upvotes: 1
Reputation: 237060
You seem to be asking about implementation issues. ECMAScript doesn't put strict requirements on how most data types and operations must be implemented. As long as the language behaves according to the spec, what actually happens in the hardware is up to the implementation.
Implementing function objects with function pointers is an obvious way to do it, but it is not by any means required. We can say that, from the language's perspective, both variables now reference the same function object — but how that's implemented in terms of memory layout is technically up to the whoever's writing your flavor of JavaScript.
Upvotes: 0
Reputation: 14800
The answer is 'Yes' — if callThat
returns a function then...
var thisThing = callThat(someVar);
console.log(typeof thisThing); // outputs "function"
thisThing(someParam); // call the function returned by "callThat" with a parameter
Upvotes: 0
Reputation: 39532
In JavaScript, everything that isn't a primitive (string
, number
, boolean
, null
, undefined
) is passed by reference.
Upvotes: 3