<! Doctype html> <html> <head> <meta charset = "utf-8"> <tyle> tombol {latar belakang:#0f0;} </tyle> </head> <body> <button = "tombol" (tombol ";" Tombol ";" Tombol "; // tombol pop-up}; // Ini dalam konteks dapat dilihat sebagai tombol </script> </body> </html>Bergabunglah dengan Bind
Salinan kode adalah sebagai berikut:
var text = document.geteLementById ("text");
var button = document.getElementById ("tombol");
Button.onClick = function () {
waspada (this.id); // tombol pop-up
} .bind (teks);
// Ini dalam konteks dapat dilihat sebagai tombol
Saat ini, Anda akan menemukan bahwa ini telah berubah menjadi teks
Ini juga berlaku dalam literal fungsi, dengan tujuan menjaga arah naik dan turun (ini) tidak berubah.
var obj = {color: "#ccc", elemen: document.geteLementById ('text'), events: function () {document.geteLementById ("tombol"). addeventListener ("klik", function (e) {console.log (this); this.element.style.color (e) {console. {this.events ();}}; obj.init ();Saat ini, mengklik teks tombol akan berubah warna. Dapat dilihat bahwa ini bukan tombol tetapi OBJ.
Metode Bind () tidak berlaku dalam IE, 6, 7, 8. Penting untuk memperpanjang metode ini dengan memperluas prototipe fungsi.
if (! function.prototype.bind) {function.prototype.bind = function (obj) {var slice = [] .slice, args = slice.call (argumen, 1), self = this, nop = function () {}, bound = function () {return self.Apply (instance nop = this: This: This: ini: {}), args.concat (slice.call (argumen)));}; nop.prototype = self.prototype; bound.prototype = new nop (); return bound;};}Pada saat ini, Anda dapat melihat bahwa Bind () juga didukung dalam IE6, 7, dan 8.
Salinan kode adalah sebagai berikut:
slice = array.prototype.slice,
atau
array = array.prototype.slice.call (array, 0);
Konversi array seperti array