<! doctype html> <html> <head> <meta charset = "utf-8"> <style> ปุ่ม {พื้นหลังสี:#0f0;} </style> </head> <body> <button id = "ปุ่ม"> ปุ่ม </button> {แจ้งเตือน (this.id); // ปุ่มป๊อปอัพ}; // สิ่งนี้ในบริบทสามารถมองเห็นเป็นปุ่ม </script> </body> </html>เข้าร่วม Bind
การคัดลอกรหัสมีดังนี้:
var text = document.getElementById ("ข้อความ");
ปุ่ม var = document.getElementById ("ปุ่ม");
button.onclick = function () {
การแจ้งเตือน (this.id); // ปุ่มป๊อปอัพ
}. -bind (ข้อความ);
// สิ่งนี้ในบริบทสามารถมองเห็นเป็นปุ่ม
ในเวลานี้คุณจะพบว่าสิ่งนี้เปลี่ยนเป็นข้อความ
นอกจากนี้ยังมีผลบังคับใช้ในตัวอักษรฟังก์ชั่นโดยมีวัตถุประสงค์เพื่อรักษาทิศทางขึ้นและลง (สิ่งนี้) ไม่เปลี่ยนแปลง
var obj = {color: "#ccc", องค์ประกอบ: document.getElementById ('ข้อความ'), เหตุการณ์: ฟังก์ชัน () {document.getElementById ("ปุ่ม"). addeventListener ("คลิก", ฟังก์ชั่น (e) {console.log (นี่); {this.events ();}}; obj.init ();ในเวลานี้การคลิกที่ข้อความปุ่มจะเปลี่ยนสี จะเห็นได้ว่านี่ไม่ใช่ปุ่ม แต่เป็น OBJ
วิธีการของ BIND () ไม่สามารถใช้ได้ใน IE, 6, 7, 8. จำเป็นต้องขยายวิธีนี้โดยการขยายต้นแบบฟังก์ชัน
if (! function.prototype.bind) {function.prototype.bind = function (obj) {var slice = [] .slice, args = slice.call (อาร์กิวเมนต์, 1), self = this, nop = function () {}, bound = function () {return self.apply {}), 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);
แปลงอาร์เรย์เป็นอาร์เรย์