0

I am trying this in Chrome on a Mac:

function SoundRecorder() {
}

SoundRecorder.prototype.recordSound = function() {
  navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  if (!navigator.getUserMedia) {
    alert('Media is not supported in your browser');
    return;
  }
  navigator.getUserMedia({
    audio: true
  }, this.success, this.failure);
};

SoundRecorder.prototype.success = function(e) {
  console.log(this == window);
};

SoundRecorder.prototype.failure = function() {
  return alert('You denied permission');
};

When I run new SoundRecorder().recordSound() it prints out true. Shouldn't the value of this be an 'instance' of SoundRecoder. I am missing something or is this a Chrome Bug?

I tried it in Firefox and the value of this was "SoundRecorder.prototype.success"

dg428
  • 413
  • 6
  • 14

1 Answers1

1

You can set the correct this by keeping a closure to the instance, then setting it as this in the call:

SoundRecorder.prototype.recordSound = function() {

  // Keep reference to this, i.e. instance calling the method
  var soundRecorder = this;

  navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia ||
                           navigator.mozGetUserMedia || navigator.msGetUserMedia;
  if (!navigator.getUserMedia) {
    alert('Media is not supported in your browser');
    return;
  }

  navigator.getUserMedia({audio: true},

                         // Call the functions, setting their this to the instance
                         function() {soundRecorder.success()},
                         function() {soundRecorder.failure()}
  );
};

The duplicate answer referenced by Bergi says that.

RobG
  • 142,382
  • 31
  • 172
  • 209