Necesito acceder al objeto principal (no a la window ) en un detector de eventos.
En realidad, obtengo window con self y el objeto WebSocket (objetivo de escucha de eventos) con this . Quiero obtener el objeto ScratchCloud (padre).
Aquí está el código JS:
var ScratchCloud = function(url, user, project) { "use strict"; this.socket = new WebSocket(url); // Create socket this.ws_status = function() { var status = this.socket.readyState; var message = "Scratch Cloud Data Socket ("; switch (status) { case 0: message += "Connecting"; case 1: message += "Open"; case 2: message += "Closing"; case 3: message += "Closed"; } message += ")" return message; } this.ws_log = function(message, func, symbol) { if (!func) { func = console.log; } if (symbol) { func(this.ws_status(), symbol, message); } else { func(this.ws_status() + ":", message); } }; this.ws_open = function(event) { console.log(self === window); self.ws_log(); var handshake = { method: "handshake", user: user, project: project }; handshake = JSON.stringify(handshake) + "\n"; self.ws_log(handshake, null, ">>"); event.target.send(handshake); self.ws_log(); } this.ws_error = function(event) { this.ws_log(console.error, event, ">>"); }; this.ws_message = function(event) { this.ws_log(console.log, event, ">>"); }; this.ws_close = this.ws_message; this.socket.onopen = this.ws_open; this.socket.onerror = this.ws_error; this.socket.onmessage = this.ws_message; this.socket.onclose = this.ws_close; }; new ScratchCloud("wss://clouddata.scratch.mit.edu/", "<user-name>", "<scratch-project>"); ¿Cómo acceder a la instancia de ScratchCloud en la función ws_open ? Busqué sobre this y sobre mí self , pero no puedo encontrar nada.
Aquí, el problema es this . Primero, has aprendido sobre this en JS. Cuando invoca la función con self , no funciona y no accede al objeto de la window . Y cuando usa this , está llamando al objeto WebSocket . ¿Derecha?
Si desea hacer que this use la función ScratchCloud , debe bind this explícitamente con la función ScratchCloud . Los siguientes recursos lo ayudarán a comprender el enlace explícito en JS:
this palabra clave + 5 reglas de enlace de teclas explicadas para principiantes de JSEspero que lo anterior te ayude.