如何从闭包中获取对象? [英] how to get an object from a closure?

查看:47
本文介绍了如何从闭包中获取对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从闭包中获取对象,这让我感到困惑,这是一个问题:

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]
       }
   } 
}

问题:如何在不更改源代码的情况下获取原始的 person 对象.

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

这可以工作,因为所有对象都继承了 Object.prototype ,因此您可以向其中插入一个getter,该方法可以通过 this 访问该对象,然后可以使用公开的运行方法来执行该吸气剂.

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.

这篇关于如何从闭包中获取对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆