Siempre he tenido un sentimiento plausible sobre esto en JavaScript. Hoy de repente me sentí iluminado. Lo grabaré aquí.
Veamos primero una castaña:
<! Doctype html> <html> <adead> <meta charset = "utf-8"> <title> usando esto </title> <script type = "text/javascript"> var car, tesla; car = function () {this.start = function () {console.log ('Car inicial');}; this.turnkye () carkey = document.getElementById ('car_key'); carkey.onClick = function () {this.start (); };} return this;} tesla = new Car (); tesla.turnkye (); </script> </head> <body> <input type = "button" id = "car_key" value = "test"/> </bod> </html>A primera vista, no hay problema con este código, pero la comprensión incorrecta de esto finalmente lleva al resultado incorrecto. Vinculamos el evento de clic en el elemento car_key, y creemos que anidar el evento de clic de encuadernación en la clase de automóviles puede permitir que este elemento DOM acceda al automóvil en este contexto. Este método parece razonable, pero desafortunadamente no funciona.
En JavaScript, esta palabra clave siempre apunta al propietario del alcance que se está ejecutando.
Por favor, comprenda cuidadosamente la oración anterior. Como sabemos, las llamadas de funciones producirán un nuevo alcance, y se activa un pequeño evento OnClick, y esto apunta al elemento DOM en lugar de la clase de automóvil.
Entonces, ¿cómo lo hacemos para que funcione correctamente? Por lo general, asignamos esto a una variable libre local (como esa, _as, yo, yo, etc., que se reflejan en muchos marcos) para evitar los problemas causados por el alcance. Aquí usamos variables locales para anular el método anterior:
<! Doctype html> <html> <fead> <meta charset = "utf-8"> <title> uso de este </title> </head> <body> <input type = "button" id = "car_key" valor = "test"/> <script type = "text/javaScript"> var car, tesla; car = function () inicio ');}; this.Turnkye = function () {var that = this; var carkey = document.getElementById (' car_key '); carkey.onClick = function () {that.start (); };} return this;} tesla = new Car (); tesla.turnkye (); </script> </body> </html>Como esa es una variable gratuita, la partida del evento OnClick no causa su redefinición.
Si está familiarizado con ES6, puede usar el símbolo de flecha de grasa, que es más simple y más fácil de entender, de la siguiente manera:
<! Doctype html> <html> <fead> <meta charset = "utf-8"> <title> uso de este </title> </head> <body> <input type = "button" id = "car_key" valor = "test"/> <script type = "text/javaScript"> var car, tesla; car = function () inicio ');}; this.Turnkye = function () {// var que = this; var carkey = document.getElementById (' car_key '); // carkey.onclick = function () {// that.start (); //};carkey.onclick=()=>This.start() ;HetReturn this;} tesla = new Car (); tesla.Turnkye (); </script> </body> </html>Por supuesto, también podemos usar el método de función de enlace para resolver este problema: de la siguiente manera
<! Doctype html> <html> <fead> <meta charset = "utf-8"> <title> uso de este </title> </head> <body> <input type = "button" id = "car_key" valor = "test"/> <script type = "text/javaScript"> var car, tesla; car = function () inicio ');}; var click = function () {this.Start (); } this.turnkye = function () {// var that = this; var carkey = document.getElementById ('car_key'); carkey.onClick = click.bind (this);} return this;} tesla = new Car (); tesla.turnkye (); </script> </body> </html>De hecho, solo sabía cómo escribir estas trampas cuando estaba aprendiendo a Reaccionar y cuando era eventos vinculantes. En ese momento, solo sabía cómo escribirlos así, pero no sabía lo que pasó. Hoy de repente me sentí iluminado. Espero que sea útil para todos.