
前回のエントリー「Function.call()の使い道」に関して、いくつか間違い(というか僕の勘違い)があったので、真・Function.call()の使い道、リベンジエントリーです。
この内容は、AS2、3共通の内容になります。同じ考え方でそれぞれ活用できます。今回のコードは、AS2で説明します。
Function.call()は、第一引数に指定するスコープで、任意のFunctionを呼び出すことができるという便利メソッドです。
例えば、AS2において、こんなコードがあったとします。(Test.as)
class Test {
var basemc;
function Test(mc) {
basemc = mc;
init();
}
function init(){
basemc.btn.onRelease = function() {
start();
}
}
function start() {
trace("start!");
}
}
フレームアクションは、var t = new Test(this);
このとき、btn.onRelease内のstart();はfunction start()を見つけることができないので、上のコードは実行できません。(フレームアクションですべて書いた場合は、実行可能です。)
なので、下記のように修正できます。
class Test {
var basemc;
function Test(mc) {
basemc = mc;
init();
}
function init(){
var scope = this;
basemc.btn.onRelease = function() {
scope.start();
}
}
function start() {
trace("start!");
}
}
関数の中で作った変数ならば、btn.onRelease内から参照することができるので、var scope = this;という風にbtn.onRelease外のスコープを保持しておいて、それを利用して、scope.start();を指定してやることができます。
で、本題のFunction.call()という関数についてですが、これの応用的なことができるのです。
class Test {
var basemc;
function Test(mc){
basemc = mc;
}
function init() {
var scope = this;
basemc.btn.onRelease = function () {
new CallbackFunction(scope.helloWorld, scope);
}
}
function helloWorld() {
say();
}
function say() {
trace("hello world");
}
}
というコードで、下記のCallbackFunction.asを呼び出します。
class CallbackFunction {
var callback;
var callbackScope;
function CallbackFunction(func, scope) {
callback = func;
callbackScope = scope;
init();
}
function init() {
callback.call(callbackScope);
}
}
引数で与えられた関数が、引数で与えられたスコープで実行されます。
つまり、ここで指定しているcallbackScopeは、Test.asのscopeを指しているのです。
で、大丈夫ですよね。


コメント (2)
ソース長くなってるよ!w
何に使うの?
投稿者: iotf | 2008年01月31日 21:22
例えば
var scope = this;
unko_btn.onRelease = function() {
new iotfTween(this, {duration:12, _xscale:200, callback:scope.helloworld, scope:scope});
}
function helloworld(){
trace("unkounko");
}
とか。自作モーションクラスを作ってモーションが終わった後にコールバックするファンクションを送るとか、何か色々使い道はあると思うわん。
投稿者: feb19 | 2008年02月01日 00:46