how to get an object from a closure?

江枫思渺然 提交于 2021-02-07 07:57:11

问题


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.


回答1:


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.




回答2:


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"));



回答3:


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)



回答4:


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




回答5:


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>


来源:https://stackoverflow.com/questions/54808157/how-to-get-an-object-from-a-closure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!