Why Is This Javascript Function Producing This Output?
Solution 1:
I write
obj1 = MyObject1(1, 2) // {"myA" :1,"myB" :2}
Can someone explain me why?
Cause MyObject
is a function that returns an object, therefore if you call it it returns an object :)
when I write:
obj1.myA;
why does the answer remain 1, it is because hello is a closure?
Cause you created a new object, and that object has got a property myA
which was set to 1
during construction. Then you assigned that new object to the global variable obj1
, so you can access it whenever you want. Closures are only involved if you got a function inside another function, for example if you would do:
varMyObject1 = function (a, b) {
return {
myA : a,
myB : b,
hello : function () { return a; }
} ;
} ;
Then a
is closured inside hello
, so you can do:
MyObject1(1,2).hello() // 1
Solution 2:
basically lets check all the code:
var MyObject1 = function (a, b) {}
this is a function
assignation, you can redefine this as
function MyObject1(a,b){}
lets continue with the return
statement of the function
return { ... }
here you are returning an Object
so it would be what you will have assigned on the variable that you are assignating with the return of your function.
let obj1 = MyObject1(1, 2)
here we can see that you are assigning the return
of the MyObject1(1,2)
to the obj1
variable, and the return
is an object
that you build dynamically each time that you call MyObject1
.
and at the end you ask why obj1.myA;
is 1
right? this is easy, you created and object with the following properties based on the parameters of the object construction, in this case (1, 2)
:
{
myA:1,
myB:1,
hello:function()
}
this it is clear why the value of obj1.myA
is 1
.
varMyObject1 = function(a, b) {
return {
myA: a,
myB: b,
hello: function() {
return"Hello !";
}
};
};
let obj1 = MyObject1(1, 2);
console.log(obj1);
console.log(obj1.myA);
Post a Comment for "Why Is This Javascript Function Producing This Output?"