1

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.

4 Answers 4

3

In JavaScript, everything that isn't a primitive (string, number, boolean, null, undefined) is passed by reference.

Sign up to request clarification or add additional context in comments.

3 Comments

Additionally, so that it's more clear to OP, functions are considered "first-class citizens".
Ok. So I gather that functions are pointers just as any other object.
Just to clarify, JavaScript definitely does not pass by reference. It always passes by value, even for objects. But for objects, the value that it passes is a reference. If it was pass by reference, then function makeNull(val){val = null}; makeNull(alert); would actually change the value of the alert function to null. But it doesn't, because alert is passed by value.
1

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.

1 Comment

cool. that's a neat example. i suppose the same would apply if obj1 and obj2 were applied to functions.
0

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

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.