2015-07-21 108 views
0

我有一个快速问题。我正在与peerjs进行视频聊天,并收到该函数未定义的错误。下面是代码:如何调用回调函数中的继承函数

主要构造VoIP是被称为在其他文件中像

var voip = new Voip(); 

这是函数:

function Voip(options) { 
var self = this; 

options = options ||  {}; 

var allOptions = _.extend({ 
secure: true, 
debug: 3 
}, options); 

this.peerjs = new Peer(allOptions); 

第一个问题就在这里。我怎么能通过监听呼叫事件函数otherCall在底部来调用otherCall里面的回调函数。现在用this.otherCall写出来,但这不起作用。每当我收到通话事件并接听电话时,我都会想去这个功能。

this.peerjs.on('call', function(call){ 
call.answer(window.localStream); 
this.otherCall(call); 
    }); 
} 

然后通过继承EventEmitter来扩展Voip。我可以完全摆脱这条线,仍然保持相同的功能?我根本不使用EventEmitter,而是在我帮助的代码中使用它。

Voip.prototype = _.extend(EventEmitter.prototype, { 

同样在这里,self.otherCall不起作用。解决办法是什么?

callOther: function(receiverId) { 
var self = this; 
var call = self.peerjs.call(receiverId, window.localStream); 
self.otherCall(call); 
}, 

otherCall: function(call) { 

if (window.existingCall) { 
    window.existingCall.close(); 
    } 

call.on('stream', function(stream){ 
$('iframe').putthecodein....(stream) 
    }); 
    window.existingCall = call; 
} 
}); 

希望我在我的问题中已经很清楚。如果我总结一下我想在调用事件时调用函数otherCall,并且在调用其他函数时第二次调用函数otherCall。并且为了继承EventEmitter,我想知道我是否可以通过这种方式修改代码,使得我不需要这条线,一切仍然正常。

+0

在你的'call'事件中,你的'otherCall'行会抛出错误吗? 'callOther'函数的同样问题。你有没有试过记录'this'在'call'事件中的内容,'callOther'函数中有'self'。这可能是一个范围问题。 –

+0

@TahirAhmed在该行的两种情况下都不能调用'otherCall'。 'callOther'里面的'self'是Voip对象,而'this'里面的call事件是未定义的。 – Prototype

+0

你的'otherCall'函数是在'Voip'对象中定义的还是只是一个全局函数? –

回答

2

像这样使用。它可能工作。

var self = this; 

self.peerjs.on('call', function(call){ 
    call.answer(window.localStream); 
    self.otherCall.call(self, call); 
}); 
+0

它确实工作,调用函数,但然后我有问题在这行'call.on('stream',function(stream)''otherCall'函数内部,它说它不能读取未定义的属性'on'。 – Prototype

+0

问题在于没有正确接收流。在溪流开放之前被调用。 – Prototype