Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get an object from a closure?

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.

like image 648
芝华塔尼欧 Avatar asked Jan 02 '23 06:01

芝华塔尼欧


1 Answers

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.

like image 159
Jonas Wilms Avatar answered Jan 03 '23 20:01

Jonas Wilms