简体   繁体   中英

JavaScript proxy objects don't work

JavaScript proxy objects in Firefox don't seem to work on web audio objects.

For example:

audio = new AudioContext();
s = audio.createOscillator();
s0 = new Proxy (s, {});
s0.connect(audio.destination);
s0.start();

The above code should forward all operations on s0 to s. However, I get errors like:

"TypeError: 'start' called on an object that does not implement interface OscillatorNode."

I've searched for any info on this, but have not found anything relevant. Is this a known bug / limitation? Are these objects not proxiable for some definate reason?

Thanks for any info on this.

-- Rich

The problem is that, when you call a method on a proxy, the method will receive the proxy as the this value, not the underlying object.

function Constructor() {}
Constructor.prototype.method = function() {
  return this;
};
var obj = new Constructor(),
    proxy = new Proxy(obj, {});
obj.method(); // obj
proxy.method(); // proxy

In this case, your AudioContext instance is a non-standard object, so the implementation can have implementation defined internal data stored on it, which can be used to know whether it's an AudioContext or not. Since proxy objects only redirect essential internal methods, it can be detected that it's not an AudioContext instance.

If you really need to use a proxy wrapper, you can try adding a get trap:

var audio = new AudioContext(),
    s = audio.createOscillator();
s0 = new Proxy (s, {
  get: function(target, property, receiver) {
    var val = target[property];
    if(typeof val !== 'function') return val;
    return function(...args) {
      var thisVal = this === receiver ? target : this; /* Unwrap the proxy */
      return Reflect.apply(val, thisVal, args);
    }
  }
});
s0.connect(audio.destination);
s0.start();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM