芝华塔尼欧
芝华塔尼欧

Reputation: 41

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.

Upvotes: 4

Views: 354

Answers (5)

Cb Pcbrain
Cb Pcbrain

Reputation: 16

Simply you can make this

<script type="text/javascript">
 var o = function () {
  var person = {
   name: 'jonathan',
   age: 24
  }
  return {
   run: function (key) {
       return person[key]
   }
  } 
 }
let a = new o;
alert(a.run('name'));
</script>

Upvotes: -2

Jonas Wilms
Jonas Wilms

Reputation: 138257

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.

Upvotes: 10

RexHuynh
RexHuynh

Reputation: 7

o().run("name") It will be return "jonathan".

Upvotes: -2

James Coyle
James Coyle

Reputation: 10398

Could just toString the function, pull out the part you need, and eval it to get it as an object. This is pretty fragile though so getting it to work for different cases could be tough.

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

var person = eval('(' + o.toString().substr(30, 46) + ')')

console.log(person)

Upvotes: 1

NullDev
NullDev

Reputation: 7303

You can get the keys by running

o().run("<keyname>"))

Like that:

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

console.log(o().run("name"));
console.log(o().run("age"));

Upvotes: 2

Related Questions