how to get an object from a closure?

  • A+
Category:Languages

How to get an object from a closure, that's confusion with me, here is the question:

var o = function () {    var person = {        name: 'jonathan',        age: 24    }    return {        run: function (key) {            return person[key]        }    }  } 

question: How do i get original person object without changing the source code.

 


var o = function() {   var person = {     name: 'jonathan',     age: 24   }   return {     run: function(key) {       return person[key]     }   } }  Object.defineProperty(Object.prototype, "self", {   get() {     return this;   } });  console.log(o().run("self")); // logs the object

This works as all objects inherit the Object.prototype, therefore you can insert a getter to it, which has access to the object through this, then you can use the exposed run method to execute that getter.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: