我在Mac上的Chrome中尝试此操作:
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');
};
我跑的时候
new SoundRecorder().recordSound()
它打印出真实。它的值不应该是SoundRecoder的“实例”。我错过了什么或者这是Chrome Bug?
我在Firefox中试过它,其价值是“SoundRecorder.prototype.success”
答案 0 :(得分:1)
您可以通过对实例保持闭包,然后在调用中将其设置为 this 来设置正确的 this :
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()}
);
};
Bergi引用的重复答案说明了这一点。