-4

I have a question about this fonction:

var MyObject3 = function (a, b) {
   var obj = { myA : a, myB : b } ;
   obj.foo = function () { return obj.myA + obj.myB ; } ;
   obj.bar = function (c) { return obj.myA + c ; } ;
   return obj ;
} ;

obj.foo and obj.bar are closures(what i understand). I write first:

 obj3 = MyObject3(1, 2) ;

and the result is: {"myA" :1,"myB" :2}. This is OK. I try to change the value of obj3.myA : > obj3.myA = 4 ; obj3 ; and the result is : {"myA" :4,"myB" :2} . What I don't understand is: why > obj3.foo() ; returns 6? obj3.foo() gives 6 as a result ? obj3.foo() is supposed to be a closure isn'it ? its result should be;3 ?

5
  • 1
    Is this today's homework? stackoverflow.com/questions/50493579/closures-javascript/… Commented May 23, 2018 at 18:17
  • Thought the code looked similar. lol Commented May 23, 2018 at 18:18
  • 1
    Don't be so angry folks. Understanding the basic theoretical concepts is sometimes the most difficult part, there's nothing bad about asking questions Commented May 23, 2018 at 18:31
  • 1
    @NikitaIsaev Oh, no anger or hostility intended at all. You're correct that understanding the basics can be challenging but the road to knowledge is one of exploration, not outsourcing. Commented May 23, 2018 at 18:46
  • @FissureKing chances are, on his own he would finally come to an incorrect understanding Commented May 23, 2018 at 18:53

1 Answer 1

1

Function MyObject3 defines a variable in its scope, which refers to a newly created object:

var obj = { myA : a, myB : b } ;

All references to obj inside of that function's scope refer to that object. Than the object is returned by the function and saved to the variable obj3. obj inside of the MyObject3 scope and obj3 in the global scope thus refer to the same object.

In javascript, primitives (e.g. numbers, booleans, strings) are passed by value, whereas objects are passed by reference. Which means that:

var val1 = 1;
var val2 = val1;
val1 = 4;
console.log(val2); // will log 1

// but:

var obj1 = {foo: 'bar'};
var obj2 = obj1;
obj1.foo = 'baz';
console.log(obj2.foo); // will log 'baz'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.