<! Doctype html> <html> <fead> <meta charset = "utf-8"> <style> botón {en segundo plano:#0f0;} </ystye> </head> <body> <button id = "botón"> botón </button> <input type = "text"> <script> var button = document.getElementByid ("botón); button.onclick-cclick () {alerta (this.id); // botón emergente}; // Esto en el contexto puede verse como un botón </script> </body> </html>Unirse a Bind
La copia del código es la siguiente:
var text = document.getElementById ("Text");
var button = document.getElementById ("botón");
button.OnClick = function () {
alerta (this.id); // botón emergente
} .bind (texto);
// Esto en el contexto puede verse como un botón
En este momento, encontrará que esto ha cambiado a texto
También es aplicable en literales de funciones, con el propósito de mantener la dirección hacia arriba y hacia abajo (esto) sin cambios.
var obj = {color: "#ccc", elemento: document.getElementById ('text'), events: function () {document.getElementById ("botón"). addEventListener ("click", function (e) {console.log (this); this.sement.style.color = this.color;}. {this.events ();}}; obj.init ();En este momento, hacer clic en el texto del botón cambiará de color. Se puede ver que este no es un botón sino obj.
El método de bind () no es aplicable en IE, 6, 7, 8. Es necesario extender este método extendiendo el prototipo de función.
if (? {}), args.concat (slice.call (argumentos)));}; nop.prototype = self.prototype; bound.prototype = new nop (); return Bound;};}En este momento, puede ver que Bind () también es compatible con IE6, 7 y 8.
La copia del código es la siguiente:
slice = array.prototype.slice,
o
array = array.prototype.slice.call (array, 0);
Convertir una matriz como a una matriz