Javascript Challenges

Closures and Objects

As you know Javascript has two different ways to treat the data it receives as arguments of a function:

  • Primitives are passed by copy.
  • Objects are passed by reference.

See the following code:

var oPerson = { name: 'john' };

(function(oTeacher) {
   window.getTeacher= function() {
      console.log(oTeacher);
   };
}(oPerson));

window.getTeacher();

oPerson.surname = 'doe';

window.getTeacher();

oPerson = { name: 'mary', surname: 'sullivan' };

window.getTeacher();

The first execution of window.getTeacher returns:

Object { name: "john" }

The second execution of window.getTeacher returns:

Object { name: "john", surname: "doe" }

The third execution of window.getTeacher returns:

Object { name: "john", surname: "doe" }

Exercise

Correct!
False!

Explain why this is happening:

Exercise

Correct!
False!

Fix the code to make the third execution return Object { name: "mary", surname: "sullivan" }

var oPerson = { name: 'john'}; (function(oTeacher) { window.getTeacher= function() { console.log(oTeacher); }; }(oPerson)); window.getTeacher(); oPerson.surname = 'doe'; window.getTeacher(); oPerson = { name: 'mary', surname: 'sullivan' }; window.getTeacher();