this 属性

this

引用对象或影片剪辑实例。执行脚本时,this 引用包含该脚本的影片剪辑实例。在调用字段时,this 包含对包含所调用字段的对象的引用。

在附加到按钮的 on() 事件处理函数中,this 引用包含该按钮的时间轴。在附加到影片剪辑的 onClipEvent() 事件处理函数中,this 引用该影片剪辑自身的时间轴。

因为 this 是在包含它的脚本的上下文中计算的,所以您不能在脚本中使用 this 来引用在类文件中定义的变量。创建 ApplyThis.as,并输入下面的代码:

class ApplyThis {
var str:String = "Defined in ApplyThis.as";
function conctStr(x:String):String {
return x+x;
}
function addStr():String {
return str;
}
}

然后,在 FLA 或 AS 文件中,添加下面的 ActionScript:

var obj:ApplyThis = new ApplyThis();
var abj:ApplyThis = new ApplyThis();
abj.str = "defined in FLA or AS";
trace(obj.addStr.call(abj, null)); //output: defined in FLA or AS
trace(obj.addStr.call(this, null)); //output: undefined
trace(obj.addStr.call(obj, null)); //output: Defined in applyThis.as

同样,若要调用在动态类中定义的函数,您必须使用 this 在适当范围内调用该函数:

// incorrect version of Simple.as
/*
dynamic class Simple {
function callfunc() {
trace(func());
}
}
*/
// correct version of Simple.as
dynamic class simple {
function callfunc() {
trace(this.func());
}
}

在 FLA 或 AS 文件中,添加下面的 ActionScript:

var obj:Simple = new Simple();
obj.num = 0;
obj.func = function() {
return true;
};
obj.callfunc();
// output: true

如果使用版本不正确的 Simple.as,则会产生一个语法错误。

示例

在下面的示例中,关键字 this 引用 Circle 对象:

function Circle(radius:Number):Void {
 this.radius = radius;
 this.area = Math.PI*Math.pow(radius, 2);
}
var myCircle = new Circle(4);
trace(myCircle.area);

在下面分配给影片剪辑内的帧的语句中,关键字 this 引用当前的影片剪辑。

// sets the alpha property of the current movie clip to 20
this._alpha = 20;

在下面的 MovieClip.onPress 处理函数内的语句中,关键字 this 引用当前的影片剪辑:

this.square_mc.onPress = function() {
 startDrag(this);
};
this.square_mc.onRelease = function() {
 stopDrag();
};

请参阅

on 处理函数, onClipEvent 处理函数