最終更新:2018-01-08 (月) 03:59:23 (2262d)
bind
Top / bind
- JavaScript 1.8.5でFunction.prototype.bind() メソッドが導入されました。これは呼び出す関数内で this に相当する値を指定できるものです。これを使えば、関数がどこから呼び出されるかによって this の値が変わってしまうというややこしい問題を簡単に回避できます。
var Something = function(element) { this.name = 'Something Good'; this.onclick1 = function(event) { console.log(this.name); // this は element なので undefined になります }; this.onclick2 = function(event) { console.log(this.name); // this はバインドされた Something オブジェクトなので「Something Good」と出力されます }; element.addEventListener('click', this.onclick1, false); element.addEventListener('click', this.onclick2.bind(this), false); // これが仕掛けです }