<! doctype html> <html> <head> <meta charset = "utf-8"> <style> زر {خلفية اللون:#0f0 ؛} </style> </head> <body> <button> button. {Alert (this.id) ؛ // زر المنبثقة} ؛ // يمكن اعتبار هذا في السياق زرًا </script> </body> </html>انضم إلى الربط
نسخة الكود كما يلي:
var text = document.getElementById ("text") ؛
var button = document.getElementById ("button") ؛
button.onclick = function () {
تنبيه (this.id) ؛ // زر المنبثقة
} .bind (text) ؛
// هذا في السياق يمكن اعتباره زر
في هذا الوقت ، ستجد أن هذا قد تغير إلى نص
كما ينطبق في الحرفية الوظيفة ، مع الغرض من الحفاظ على الاتجاه لأعلى ولأسفل (هذا) دون تغيير.
var obj = {color: "#ccc" ، العنصر: document.getElementById ('text') ، الأحداث: function () {document.getElementById ("button"). addeventListener ("click" ، function (e) {console.log (this) ؛ this.element.style.color = this.color ؛} {this.events () ؛}} ؛ obj.init () ؛في هذا الوقت ، سيتغير النقر على نص الزر اللون. يمكن ملاحظة أن هذا ليس زرًا بل OBJ.
لا تنطبق طريقة BIND () في IE ، 6 ، 7 ، 8. من الضروري تمديد هذه الطريقة عن طريق توسيع النموذج الأولي للوظيفة.
if (! function.prototype.bind) {function.prototype.bind = function (obj) {var slice = [] {}) ، args.concat (slice.call (الوسائط)))) ؛} ؛ nop.prototype = self.prototype ؛ bound.prototype = new nop () ؛ return bound ؛} ؛}في هذا الوقت ، يمكنك أن ترى أن BIND () مدعوم أيضًا في IE6 و 7 و 8.
نسخة الكود كما يلي:
slice = array.prototype.slice ،
أو
Array = Array.Prototype.slice.call (Array ، 0) ؛
تحويل مجموعة مثل صفيف