如何访问本机对象调用的函数中的实例?
我承认我已经问过有关 this
关键字及其在某些情况下的含义的问题,但恐怕我仍然没有完全理解它。任何提示将不胜感激。
我基本上有一个 Socket 类,它是 HTML5 的 WebSocket 类的包装器,以使事情变得更容易(我只复制了与我的问题相关的内容):
var Socket = function(url) {
this.url = url;
this.webSocket = null;
}
Socket.prototype.init = function() {
this.webSocket = new WebSocket(this.url);
this.webSocket.onmessage = this.parseMessage;
};
Socket.prototype.parseMessage = function(event) {
console.log(this); // logs the WebSocket (native) instance
}
在 parseMessage 函数中, this
指的是实例本地 WebSocket
对象的实例,那么我如何在这里访问我的 Socket
对象的实例呢?
多谢。
I admit that I've already asked a question about the this
keyword and what it means in certain situations, but I still do not completely understand it I'm afraid. Any hints would be greatly appreciated.
I basically have a Socket class, which is a wrapper to the WebSocket class of HTML5 to make things easier (I only copied what is relevant to my question):
var Socket = function(url) {
this.url = url;
this.webSocket = null;
}
Socket.prototype.init = function() {
this.webSocket = new WebSocket(this.url);
this.webSocket.onmessage = this.parseMessage;
};
Socket.prototype.parseMessage = function(event) {
console.log(this); // logs the WebSocket (native) instance
}
In the parseMessage function, this
refers to the instance of the native WebSocket
object, so how can I access the instance to my Socket
object here?
Thanks a lot.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以
绑定
它:但是,并非所有浏览器本身都支持此功能,但您可以从 MDC 使所有浏览器兼容。
如果您不熟悉绑定...它可以让您具体指定调用该函数时
this
应该是什么。当该行运行时,this
是您的 Socket 类实例,因此您基本上是强制this
inside parseMessage 指向回该实例。如果由于某种原因,您不想使用
bind
,另一种选择是将this
的副本保存到变量中,这样事件中的含义就不会丢失派遣:You can
bind
it:However, not all browsers support this natively, but you can grab a code snippet from MDC to make all browsers compatible.
In you're unfamiliar with binding ... it lets you specify specifically what
this
should be when that function is called. At the time that line runs,this
is your Socket class instance, so you're basically forcingthis
inside parseMessage to point back to the instance.If, for some reason, you don't want to use
bind
, another option is to save a copy ofthis
to a variable so the meaning is not lost inside an event dispatch: