1、 创建一个新的Fla文档,然后在第一帧的脚本中定义一个函数:
functionshowHeart()functionshowAgain()
{
trace("ThisisshowAgainFunction");
trace("this="+this);
this.showHeart();
}
//使用代理的静态方法
varfam:Function=mx.utils.Delegate.create(_root,showAgain);
//就好象创建了一个函数指针,然后调用,
fam();接着你会发现它的输出是:
ThisisshowAgainFunction
this=_level0
ILoveU,myLittleLeaf注意:不要忘记把MC拖到主时间轴,呵呵,我刚才忘记了,顺便提一下
从这个例子,可以看出:Delagate在做什么了,它好像是创建了一个函数指针,但同时它有改变了函数的上下问。但是它只是把fam 所引用的函数改变上下文,实际的showAgain函数并没有改变上下文。不信可以再调用showAgain看看。在MC第一帧中最后再加一句调用:
showAgain();
看一下输出:
ThisisshowAgainFunction
this=_level0
ILoveU,myLittleLeaf
ThisisshowAgainFunction
this=_level0.instance1其不同点是:
前者:this=_level0 后者this=_level0.instance1。 this引用不一样。
前者:I Love U ,my Little Leaf 后者:空(没有打印即没有调用)
很明显,想一想,问题就很清楚了。
但是,这里的疑问是,Delegate是怎么做的呢?那么先看看,Delegate还有哪些方法:
function Delegate(f:Function) :这是构造函数,传入一个函数。
createDelegate(obj:Object):Function :传入一个Object返回一个函数。
这样看来。也可以使用实例化的方法来使用Delegate,刚才用的那个方法是静态方法!
再修改MC第一帧中的代码:
functionshowAgain()
{
trace("ThisisshowAgainFunction");
trace("this="+this);
this.showHeart();
this.a_txt.text="KKK";
}
//varfam:Function=mx.utils.Delegate.create(_root,showAgain);
//fam();
//showAgain();
varmydgt:mx.utils.Delegate=newmx.utils.Delegate(showAgain);
varfam:Function=mydgt.createDelegate(_root);
fam();输出结果:
和第一次几乎没有什么变化,这应该是Delegate类应用吧,呵呵比较肤浅,就是这样拉。哈哈。不过不能不联想到,我上次发的关于Function类的文章,可以确定,Delegate类和Function类的两个方法(call, apply)一定有一定的关联的。下篇讨论哦! 这个是源文件:
点击浏览该文件
上一篇:mx.utils 包 [1] 之Collection&Iterator
下一篇:flash中的stop之bug篇
共有 0 位网友发表了评论,得分 0 分,平均 0 分 查看完整评论