Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
162 views
in Technique[技术] by (71.8m points)

javascript - Any way to define ALL variables within function as property of this?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...