<! docType html> <html> <head> <meta charset = "utf-8"> <style> 버튼 {back {alert (this.id); // 팝업 버튼}; // 컨텍스트에서 이것은 버튼으로 볼 수 있습니다 </script> </body> </html>바인드 가입
코드 사본은 다음과 같습니다.
var text = document.getElementById ( "text");
var button = document.getElementById ( "버튼");
button.onclick = function () {
경고 (this.id); // 팝업 버튼
} .bind (텍스트);
// 컨텍스트에서 이것은 버튼으로 볼 수 있습니다
현재로서는 이것이 텍스트로 변경되었음을 알 수 있습니다.
또한 기능 리터럴에도 적용되며, 위아래 방향 (이)을 변경하지 않도록합니다.
var obj = {color : "#ccc", element : document.getElementById ( 'text'), events : function (). {this.events ();}}; obj.init ();현재 버튼 텍스트를 클릭하면 색상이 변경됩니다. 이것은 버튼이 아니라 obj라는 것을 알 수 있습니다.
bind ()의 방법은 IE, 6, 7, 8에 적용 할 수 없습니다. 함수 프로토 타입을 확장 하여이 방법을 확장해야합니다.
if (! function.prototype.bind) {function.prototyp.bind = function (obj) {var slice = [] .slice, args = slice.call (arguments, 1), self = this, nop = function () {}, function () {return self.apply (thistinestof nop? || {}), args.concat (slice.call (arguments)));}; 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);
어레이를 배열로 변환하십시오