简体   繁体   English

如何从闭包中获取对象?

[英]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. 问题:如何在不更改源代码的情况下获取原始person对象。

 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. 这个工作过程中的所有对象继承Object.prototype ,因此,你可以插入一个getter它,它通过访问该对象this ,那么你可以使用暴露run方法来执行吸气。

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

Could just toString the function, pull out the part you need, and eval it to get it as an object. 可以只toString功能,拉出您需要的部分,和eval它把它作为一个对象。 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) 

o().run("name")返回“jonathan”。

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM