Javascript 通过此
Javascript 通过此,javascript,Javascript,var应用; (功能(应用,PhotonSdk){ (功能(光子){ Photon.PeerManager=(函数(){ var$这个; 函数PeerManager(){ $this=这个; this.currentStatus=PhotonSdk.PhotonPeer.StatusCodes.connectClosed; this.peer=new PhotonSdk.PhotonPeer(“ws://localhost:9090”); this.peer.addPeerStatusListe
var应用;
(功能(应用,PhotonSdk){
(功能(光子){
Photon.PeerManager=(函数(){
var$这个;
函数PeerManager(){
$this=这个;
this.currentStatus=PhotonSdk.PhotonPeer.StatusCodes.connectClosed;
this.peer=new PhotonSdk.PhotonPeer(“ws://localhost:9090”);
this.peer.addPeerStatusListener(PhotonSdk.PhotonPeer.StatusCodes.connecting,this.\u onConnecting);
this.peer.addPeerStatusListener(PhotonSdk.PhotonPeer.StatusCodes.connect,this.\u onConnect);
}
PeerManager.prototype.establishConnection=函数(){
this.peer.connect();
日志(“光子正在建立连接”);
};
prototype.\u onConnecting=function(){
this.currentStatus=PhotonSdk.PhotonPeer.StatusCodes.connecting;
PeerManager.prototype.\u logConnectionState(this.currentStatus);//它可以工作
};
PeerManager.prototype.\u onConnect=函数(){
this.currentStatus=PhotonSdk.PhotonPeer.StatusCodes.connect;
this._logConnectionState(this.currentStatus);//它不工作:(
};
PeerManager.prototype.\u logConnectionState=函数(状态){
log(“光子连接是”+state+“+newdate().toTimeString());
};
返回PeerManager;
})();
})(Application.Photon | |(Application.Photon={}));
})(应用程序| |(应用程序={}),光子);
你使用的推荐信
_logConnectionState(this.currentStatus);
似乎是这样的:
PeerManager.prototype._onConnect
并不是说:
Peer Manager.prototype
基本上这是指
PeerManager.prototype._onConnect
及
与
PeerManager.prototype._onConnect._logConnectionState
wich未定义,因为该引用没有本地值/函数
正如您所看到的,“this”只有一个本地上下文总是绑定到它在向上扩展作用域时可以找到的第一个对象/函数。我的建议是,事件_onConnecting和_onConnect由PhotonSdk.PhotonPeer实例进行调度。由于您在此处添加了侦听器:
this.peer.addPeerStatusListener(PhotonSdk.PhotonPeer.StatusCodes.connecting, this._onConnecting);
this.peer.addPeerStatusListener(PhotonSdk.PhotonPeer.StatusCodes.connect, this._onConnect);
所以函数的调用是错误的
试试这个:
function PeerManager() {
$this = this;
this.currentStatus = PhotonSdk.PhotonPeer.StatusCodes.connectClosed;
this.peer = new PhotonSdk.PhotonPeer("ws://localhost:9090");
this.peer.addPeerStatusListener(PhotonSdk.PhotonPeer.StatusCodes.connecting, this._onConnecting.bind(this));
this.peer.addPeerStatusListener(PhotonSdk.PhotonPeer.StatusCodes.connect, this._onConnect.bind(this));
}
当您使用prototype时,它被绑定到一个对象。您必须实例化一个对象才能使用它。默认情况下,
此
将指向全局范围,而全局范围将没有\u logConnectionState
this.peer.addPeerStatusListener(PhotonSdk.PhotonPeer.StatusCodes.connecting, this._onConnecting);
this.peer.addPeerStatusListener(PhotonSdk.PhotonPeer.StatusCodes.connect, this._onConnect);
function PeerManager() {
$this = this;
this.currentStatus = PhotonSdk.PhotonPeer.StatusCodes.connectClosed;
this.peer = new PhotonSdk.PhotonPeer("ws://localhost:9090");
this.peer.addPeerStatusListener(PhotonSdk.PhotonPeer.StatusCodes.connecting, this._onConnecting.bind(this));
this.peer.addPeerStatusListener(PhotonSdk.PhotonPeer.StatusCodes.connect, this._onConnect.bind(this));
}