有什么方法可以将函数内的所有变量定义为此属性? [英] Any way to define ALL variables within function as property of this?

查看:60
本文介绍了有什么方法可以将函数内的所有变量定义为此属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这听起来有些荒谬,但是我正在寻找一种方法来将函数中的每个变量定义为 this 的属性.我正在寻找任何技巧,以任何可能的方式跟踪某种函数中的变量(即将它们添加到 this 对象中),而不必在每个变量定义前都加上 this..有办法吗? Proxy 是否可以?

  function(){//声明一个变量var hello ='hi'返回这个}让{hello} = function()console.log(hello)//嗨 

例如,这可行:

  function hi(){this.hello = true;返回此}hi.bind({})()//{你好:true} 

我想要的是一种将在 hi 中定义的所有变量在定义时添加到 this 对象的方法.

解决方案

您是否正在寻找可想象的最糟糕的骇客?当然,一切皆有可能:

 功能示例(){与(可怕(此)){var hello ='hi';}}var x =新示例;x.hello;//'你好'功能可怕(目标){返回新的代理(目标,{has(){返回true;},//包含您可能希望的所有变量!get(_,k){返回目标中的k?target [k] :( 1,eval)(k)}});} 

该代理声称包含所有可能在 with 范围内用作变量的名称.这基本上会导致所有未声明的变量或 var 声明的变量在目标上创建属性(除非您使用 let const ,否则它们将真正位于区块范围内.
但是,对于变量查找,不是目标属性的所有对象都将在全局范围内解析(使用全局 eval ),因为当代理表示可以传递所有变量时,原始范围无法保留.

I know this may sound a little absurd, but I'm looking for a way to define every variable within a function as a property of this. I'm looking for any hack, any way possible to be able to have some way to track variables within a function (i.e. add them to the this object) without having to actually preface every single variable definition with this.. Is there a way? Is this possible with Proxy?

function () {
  // declare a variable
  var hello = 'hi'
  return this
}

let {hello} = function()
console.log(hello) // hi

For example this works:

function hi () { this.hello = true; return this }
hi.bind({})() // { hello: true }

What I want is a way to have all variables defined within hi to be added to the this object when they are defined.

解决方案

You are looking for the worst hack imaginable? Sure, everything is possible:

function example () {
  with(horrible(this)) {
    var hello = 'hi';
  }
}
var x = new example;
x.hello; // 'hi'


function horrible(target) {
  return new Proxy(target, {
    has() { return true; }, // contains all variables you could ever wish for!
    get(_, k) { return k in target ? target[k] : (1,eval)(k) }
  });
}

The proxy claims to contain all names that could ever be used as a variable in the with scope. This basically leads to all assignments of undeclared or var-declared variables create properties on the target (unless you use let or const, they'll be truly local to the block scope).
However, for variable lookup everything that is not a target property will be resolved in the global scope (using global eval) as the original scope cannot be retained when the proxy said it can deliver all variables.

这篇关于有什么方法可以将函数内的所有变量定义为此属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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