A
A
Anton Kokarev2019-04-06 00:50:11
JavaScript
Anton Kokarev, 2019-04-06 00:50:11

JS GAS how to catch a call to a non-existent property of an object?

Using Google Apps Script (JavaScript), you need to create an object through the function constructor. The object initially does not have properties, but they can appear as they are accessed. How to track that there was a call to a non-existent property and set its default value?
Probably there is some kind of getter for the entire object that fires every time its properties are accessed?
Similarly, an object does not initially have methods, but they can be added as they are accessed. Accordingly, it is necessary to catch this event and add the necessary methods.
In JS, they seem to have added a special Proxy object for such purposes, but it is not implemented in Google App Script, or do I need to connect some special lib?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Robur, 2019-04-06
@Robur

If not, then no, the proxy will not be polyfilled. Write something like

var object = {
  prop: function (name) { this[name]=this[name] || 'my new prop value';  return this[name]}
  func: function (name) {/*аналогично*/}
}

/// где-то там дальше, вместо obj.x = 'foo'
obj.prop('x') = 'foo'

M
Maxim Stoyanov, 2019-04-06
@stomaks

I solved this issue like this.
Created a function through which I launch others.

function run ( fnc, arg ) {
try {
    // Пробуем запустить функцию
    return CORE[fnc]( arg );
  } catch ( error ) {}
}

And I wrote down all other functions in one global variable.
CORE = {
  func1: function ( data ) {
    // код
  },
  func2: function ( data ) {
    // код
  }
};

Further, when I need to call some function, I turn to run and pass it the name of the function and parameters .
run, in turn, tries to get and run the function from the global variable, and I catch errors using try catch.
In my case, I am able to run a function. lying in any hierarchy CORE.obj.obj.func1( arg );
If interested, please let me know how to do it.
---
Maxim Stoyanov (stomaks), developer of Google Apps Script .
g-apps-script.com
stomaks.me

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question