0

Can someone help me out with the code below:

function returnObj(){return this}

a = {
   name: "Eva",
   age: "12",
   getContext: returnObj
}
a.getContext // logs Object{name:"Eva", ...} which is fine.

But when I try

a = {
   name: "Eva",
   age: "12",
   getContext: function(){
      returnObj();
   }
}
a.getContext // logs undefined.

Can someone please help me understand what is going on here, and show me how I can make the 2nd piece of code return the object that called the function when I call a.getContext() just like the 1st one did.

Ayo
  • 39
  • 1
  • 5
  • 1
    `returnObj.call(this);`. – Niet the Dark Absol Mar 31 '16 at 12:23
  • This is solved with a [closure](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures) ([How do JavaScript closures work?](http://stackoverflow.com/questions/111102/how-do-javascript-closures-work)) no the [function context](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/this). var a = (function () { var obj = { name: "Eva", age: "12", getContext: function () { return obj; } }; return obj; })(); console.log(`getContext().name: ${a.getContext().name}`); – Peer Reynders Apr 05 '16 at 15:48
  • *return the object that called the function*. JavaScript had [`arguments.callee`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments/callee) but that has been removed for ES5 strict mode. – Peer Reynders Apr 05 '16 at 16:06
  • ... and the obsolete [`arguments.caller`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments/caller). – Peer Reynders Apr 05 '16 at 16:15

0 Answers0