2

I'm doing JavaScript in node.js.

I'm trying wrap an object not yet constructed, allowing calls to any object function and set/get any object attribute through the wrapper, letting the wrapper pass calls/sets/gets to the object if bound in the wrapper or throw an exception if the object is not yet bound in the wrapper. I want to be ignorant to the object. I'm seeking a general purpose mechanism allowing me to wrap any object in this fashion.

I could construct a wrapper structure holding the object

wrapper = {
    object: SomeObject
};

and address the object through wrapper dereference

wrapper.object.someFunction();

but I want to be transparent and use the following syntax instead:

wrapper.someFunction();

I have looked into the Proxy features of ECMAScript 6 but constantly came short on the apply() function trap. Is there a problem with JavaScript V8 and Node.js not being ECMAScript 6 compliant.

Any ideas?

user3840170
  • 26,597
  • 4
  • 30
  • 62

1 Answers1

0

What you want to do is to overload the "dot "operator, something very familiar to Python guys, the __getattr__ and __setattr__ functions.

Indeed, the way to do it in ECMAScript 6 is to use Proxies, and as this post says:

Proxies let you create objects that are true proxies (facades) for other objects

Javascript overloading dot

The problem is that NodeJS does not support ECMAScript 6.

So I see two solutions:

  1. Why don't you do something a bit idiomatic like, have a function o that will return the object, that way you can do

    wrapper.o().attribute = ...
    
  2. Maybe try IO.js that supports ECMAScript 6 and is compatible with Node/npm?

Community
  • 1
  • 1