Can I extend Proxy with an ES2015 class?

John L. picture John L. · Jun 9, 2016 · Viewed 10.5k times · Source

I tried to extend Proxy, like so:

class ObservableObject extends Proxy {}

I used Babel to transpile it to ES5, and I got this error in the browser:

app.js:15 Uncaught TypeError: Object prototype may only be an Object or null: undefined

I looked at the line of code it pointed to. Here's that portion of the code with arrows pointing to the offending line of code:

var ObservableObject = exports.ObservableObject = function (_Proxy) {
    _inherits(ObservableObject, _Proxy); // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    function ObservableObject() {
        _classCallCheck(this, ObservableObject);

        return _possibleConstructorReturn(this, Object.getPrototypeOf(ObservableObject).apply(this, arguments));
    }

    return ObservableObject;
}(Proxy);

Does anyone know why I might be getting this error? Is this a bug in Babel? What is supposed to happen when you try to extend Proxy?

Answer

John L. picture John L. · Nov 21, 2016

Well, I had forgotten about this question, but someone recently upvoted it. Even though you technically can't extend a proxy, there is a way to force a class to instantiate as a proxy and force all its subclasses to instantiate as proxies with the same property descriptor functions (I've only tested this in Chrome):

class ExtendableProxy {
    constructor() {
        return new Proxy(this, {
            set: (object, key, value, proxy) => {
                object[key] = value;
                console.log('PROXY SET');
                return true;
            }
        });
    }
}

class ChildProxyClass extends ExtendableProxy {}

let myProxy = new ChildProxyClass();

// Should set myProxy.a to 3 and print 'PROXY SET' to the console:
myProxy.a = 3;