Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/479.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何将对拥有成员函数的对象的引用传递给JS中注册回调的对象?_Javascript_Web Audio Api - Fatal编程技术网

Javascript 如何将对拥有成员函数的对象的引用传递给JS中注册回调的对象?

Javascript 如何将对拥有成员函数的对象的引用传递给JS中注册回调的对象?,javascript,web-audio-api,Javascript,Web Audio Api,如何传递对拥有成员函数的对象的引用,从中回调被注册到回调。。。在我试图澄清这句话之前,我会让代码窃贼说出来 function Foo() {} // class constructor Foo.prototype.bar = function() { navigator.getUserMedia({audio:true, video:false}, this._yayCallback, // permission granted callback thi

如何传递对拥有成员函数的对象的引用,从中回调被注册到回调。。。在我试图澄清这句话之前,我会让代码窃贼说出来

function Foo() {} // class constructor

Foo.prototype.bar = function() {
    navigator.getUserMedia({audio:true, video:false},
        this._yayCallback, // permission granted callback
        this._nayCallback); // permission denied callback
};

Foo.prototype._yayCallback(stream) {
    this._stream = stream; // need 'this' to be instance of Foo on which bar was called.
};
Foo.prototype._nayCallback(error) {
    window.alert("bah-humbug!");
};

var foo = new Foo();
foo.bar(); // Error: _yay/_nayCallback does not exist on global object or some such...

目标是能够通过“this”或任何其他方式访问名为
Foo.bar()
的实例,以便在授予访问权限后添加额外数据。

我不确定是否真正理解您的问题,但我假设这是在您的
导航器.getUserMedia
调用其回调时发生的

您可能希望在传递它们之前绑定它们:

Foo.prototype.bar = function() {
    navigator.getUserMedia({audio:true, video:false},
        this._yayCallback.bind(this), // permission granted callback
        this._nayCallback.bind(this)); // permission denied callback
};
这样,它们将在正确的上下文中被调用

否则,一旦执行,
回调中的此
将成为全局
窗口

请注意
Function.prototype.bind()

刚刚发现您的代码段有错误,应该是:

Foo.prototype._yayCallback = function (stream) {};
Foo.prototype._nayCallback = function (error) {};

但我想在你的代码中不是这样写的;)

真糟糕!这个把戏做得很好,谢谢。(试图把程序结构从C++移植到JS,这打破了我的头脑工作方式)是的,在snip-it转换中有一些编辑——尽管我认为从现在起我可能会采用“bah-humbug”作为我的默认错误消息。