- Thanks received
- 222
Yes, where "set of braces" is a shorthand for "new Object();".
Got it. Ok thanks. All objects are reference types and are held on the heap. Moving onto line 2?
Yes, where "set of braces" is a shorthand for "new Object();".
Also line 2 starts with an opening parentheses. How can a statement begin with an opening parenthesis?
I need a lie down.![]()
That is another awesome feature of JavaScript whereby enclosing a function in parens turns it into a function expression, which can then be immediately invoked (turning it into a valid statement).


Happy to do so. Given the following code (JavaScript), the interviewer claimed that "appVar2" needed to be returned from the function expression (using a "return" statement) to make "MyConstructor" available outside the scope of the closure created by the function expression. He claimed that by injecting appVar1 into the function expression it was being copied, implying that appVar2 referred to a separate object, hence the need to return.
This is a fundamental misunderstanding of the way JavaScript uses "pass reference by value" (described more commonly as "pass by reference") when dealing with objects.
Code:var appVar1 = {}; (function(appVar2){ appVar2.MyConstructor = function() { //... }; })(appVar1);
Mock me all you want!
Got it. Ok thanks. All objects are reference types and are held on the heap. Moving onto line 2?
Ok not seeing how appVar1 and appVar2 are in any way related? Can we clear this up before we deal with scope?
Ta.
var appVar1 = {}; //declare object literal (equiv. to "var appVar = new Object();")
//wrap an anonymous function in parens to make it an expression, and then invoke immediately on the final line, passing in appVar1 (visible inside the anonymous function as appVar2)
(function(appVar2){
//create a property named MyConstructor on appVar2 (which is a reference to the same object as appVar1), and assign an anonymous function to it
appVar2.MyConstructor = function() {
//...
};
})(appVar1);
//object "appVar1" now has a new property on it called MyConstructor pointing to the function defined above with the ellipsis inside.
Ok not seeing how appVar1 and appVar2 are in any way related? Can we clear this up before we deal with scope?
Ta.
Javascript is weird.
So to put it in a less insane way:
Code:var appVar1 = {}; function fn(appVar2){ appVar2.x = 10; } fn(appVar1)
And he doesn't understand that x is now part of appVar1?

Javascript is weird.
So to put it in a less insane way:
Code:var appVar1 = {}; function fn(appVar2){ appVar2.x = 10; } fn(appVar1)
And he doesn't understand that x is now part of appVar1?