在js中,我们会随手写下这样的代码
这时的那个this自然而然的是指的那个input,因为οnclick="bar(this);"把"bar(this);"这个语句放到了那个input的
作用域链中.
再看同样的as代码
因为mxml文件会最终编译为as类,而this在最终的类文件中指的是那个类本身,因此,这里的this指的是这个application
不过要特别注意inline itemrenderer,因为它们最终会编译到各自的类里,因此inline itemrenderer的this不是当前组件,
而是itemrenderer本身.
下面这两个例子更能明显的说明问题
js的
bar分别被attach到了一个input和一个span上,当bar函数分别执行的时候,它的变量作用域分别是对应的input和span
因此分别点击input和span的时候,this分别指向input和span
而在as中
this都是application本身
<html>
<head>
<script type="text/javascript">
function bar(o){
alert(o);
}
</script>
</head>
<body>
<input type="button" onclick="bar(this);" value="button">
</body>
</html>
这时的那个this自然而然的是指的那个input,因为οnclick="bar(this);"把"bar(this);"这个语句放到了那个input的
作用域链中.
再看同样的as代码
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
minWidth="955" minHeight="600">
<fx:Script>
<![CDATA[
private function bar(o:Object):void{
trace(o);
}
]]>
</fx:Script>
<s:Button label="bar" click="bar(this);"/>
</s:Application>
因为mxml文件会最终编译为as类,而this在最终的类文件中指的是那个类本身,因此,这里的this指的是这个application
不过要特别注意inline itemrenderer,因为它们最终会编译到各自的类里,因此inline itemrenderer的this不是当前组件,
而是itemrenderer本身.
下面这两个例子更能明显的说明问题
js的
<html>
<head>
</head>
<body>
<input type="button" value="button" id="button">
<span id="span">a span</span>
<script type="text/javascript">
function bar(){
alert(this);
}
var input=document.getElementById("button");
input.addEventListener("click",bar);
var span=document.getElementById("span");
span.addEventListener("click",bar);
</script>
</body>
</html>
bar分别被attach到了一个input和一个span上,当bar函数分别执行的时候,它的变量作用域分别是对应的input和span
因此分别点击input和span的时候,this分别指向input和span
而在as中
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
minWidth="955" minHeight="600" creationComplete="init(event)">
<fx:Script>
<![CDATA[
import mx.events.FlexEvent;
private function bar(event:MouseEvent):void{
trace(this);
}
protected function init(event:FlexEvent):void
{
button.addEventListener(MouseEvent.CLICK,bar);
label.addEventListener(MouseEvent.CLICK,bar);
}
]]>
</fx:Script>
<s:Button label="bar" id="button"/>
<s:Label text="label" id="label" y="40"/>
</s:Application>
this都是application本身