0

how can i get $self variable in this code

const $sys = {};
Object.defineProperty($sys, 'comp', {
  get: function() {
    console.log('====', $self)
  }
});

with({ $self: 1 }) {
  console.log($sys.comp);
}

with seems like only works on its scope, but not work for inner scope

please do not move defineProperty into with expression

  • 1
    You can't unless you make `$self` global. Functions use lexical scoping, not dynamic scoping, so the variables they see come from it's surrounding scope and not the scope from which it is called – Nick Parsons Nov 16 '22 at 08:48
  • thx reply first, I know the js lexical scoping, it means the scope is ensure when it declared, but i wonder if some method can change or walkaround the static scope like with-statement – programmerwy Nov 16 '22 at 13:09
  • I guess instead of the `with({ $self: 1});` you can do `$sys.$self = 1;` and then access that within your getter with `this.$self`. Or just use `const $self = 1;` instead of the `with()`. Or use a regular function call as an argument and pass your data into it as an argument – Nick Parsons Nov 17 '22 at 09:10
  • yes, it works, but in my scence, I don't know what $self is, because it's a runtime value, I want to declare $sys.comp statically and when $self appear, i can inject the scope into getter – programmerwy Nov 19 '22 at 08:53

0 Answers0