<!doctype html> <html> <head> <meta charset = "utf-8"> <style> button {background-color:#0f0;} </style> </head> <body> <ボタンID ">ボタン{alert(this.id); //ポップアップボタン}; //コンテキストでこれはボタンとして見ることができます</script> </body> </html>Bindに参加します
コードコピーは次のとおりです。
var text = document.getElementById( "TEXT");
var button = document.getElementById( "ボタン");
button.onclick = function(){
アラート(this.id); //ポップアップボタン
} .bind(text);
//これはコンテキストでボタンとして見ることができます
現時点では、これがテキストに変更されたことがわかります
また、上下方向(この)を変更せずに保つことを目的として、関数リテラルにも適用できます。
var obj = {color: "#ccc"、element:document.getElementbyid( 'text')、events: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 = [] .slice、args = slice.call.call.call.call.call.call.call.call.call.call.call.call = this、nop = function(){}、bound = function(){return self.(this Instance of || {})、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);
配列のような配列を配列に変換します