var Application;
(function (Application, PhotonSdk) {
(function(Photon) {
Photon.PeerManager = (function () {
var $this;
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);
this.peer.addPeerStatusListener(PhotonSdk.PhotonPeer.StatusCodes.connect, this._onConnect);
}
PeerManager.prototype.establishConnection = function() {
this.peer.connect();
console.log("Photon is establishing connection.");
};
PeerManager.prototype._onConnecting = function() {
this.currentStatus = PhotonSdk.PhotonPeer.StatusCodes.connecting;
PeerManager.prototype._logConnectionState(this.currentStatus); //It work
};
PeerManager.prototype._onConnect = function () {
this.currentStatus = PhotonSdk.PhotonPeer.StatusCodes.connect;
this._logConnectionState(this.currentStatus); //It isn't work :(
};
PeerManager.prototype._logConnectionState = function (state) {
console.log("Photon connection is " + state + ". " + new Date().toTimeString());
};
return PeerManager;
})();
})(Application.Photon || (Application.Photon = {}));
})(Application || (Application = {}), Photon);
如果我使用this._logConnectionState(this.currentStatus);
我收到this._logConnectionState is not a function
错误,但
PeerManager.prototype._logConnectionState(this.currentStatus);
或
$this._logConnectionState(this.currentStatus);
是工作。为什么会发生这种情况以及如何通过this
做好访问?
答案 0 :(得分:0)
PeerManager.prototype._onConnect = function () {
this.currentStatus = PhotonSdk.PhotonPeer.StatusCodes.connect;
this._logConnectionState(this.currentStatus); //It isn't work :(
};
您使用的参考资料
_logConnectionState(this.currentStatus);
on似乎就是这样:
PeerManager.prototype._onConnect
而不是:
Peer Manager.prototype
基本上这指的是
PeerManager.prototype._onConnect
和
this._logConnectionState
与
相同PeerManager.prototype._onConnect._logConnectionState
未定义,因为该引用没有本地值/函数。
如你所见"这"只有一个局部上下文总是被绑定到它在攀爬范围时可以找到的第一个对象/函数。
答案 1 :(得分:0)
我的建议是,事件_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));
}