jQuery/Prototype.js で、処理を委譲する方法。AS2 で言うところの Delegate.create です。
やりたいこと
下記のコードで、cat.showName() を実行した際に dog を表示したい。
var dog = { name: "dog", showName: function() { alert(this.name); } }; var cat = { name: "cat" }; cat.showName = dog.showName; cat.showName();//cat
ActionScript 2
まずは AS2。
import mx.utils.Delegate; var dog = { name: "dog", showName: function() { trace(this.name); } }; var cat = { name: "cat" }; cat.showName = Delegate.create(dog, dog.showName); cat.showName();//dog
Prototype.js
Prototype.js では Function.bind を使用します。
var dog = { name: "dog", showName: function() { alert(this.name); } }; var cat = { name: "cat" }; cat.showName = dog.showName.bind(dog); cat.showName();//dog
jQuery 1.4
jQuery はバージョン 1.4 から、jQuery.proxy() が追加されました。
jQuery.bind() と Prototype.js の Function.bind() は別物なので注意。
var dog = { name: "dog", showName: function() { alert(this.name); } }; var cat = { name: "cat" }; cat.showName = dog.showName.bind(dog); cat.showName();//dog