函数里可以使用this关键字,可以很方便的引用一个对象。
一般函数的 this 可以通过function.apply或function.call来修改this指向的对象。
不过在作为类的固有方法(类成员方法),则不能改变this对象。
package
{
import flash.display.Sprite;
/**
* 欢迎访问我的博客
* www.litefeel.com
* lite3@qq.com
* @author lite3
*/ public class FunctionTest extends Sprite
{
public function FunctionTest()
{
// 实例化一个对象,把这个对象分别传递给他们俩作为thisObj
var obj:Object = { };
trace("前者是真正的thisObj, 后者是传递的thisObj");
// 不能改变thisObj
test.call(this, this);
test.apply(this, [this]);
test.call(obj, obj);
test.apply(obj, [obj]);
test.call(null, null);
test.apply(null, [null]);
// 可以改变thisObj
foo.call(this, this);
foo.apply(this, [this]);
foo.call(obj, obj);
foo.apply(obj, [obj]);
foo.call(null, null);
foo.apply(null, [null]);
// 可以改变 this
function foo(_this:*):void
{
trace("function foo! ", this, "\t\t", _this);
}
}
// 不能改变this this始终指向 FunctionTest实例
private function test(_this:*):void
{
trace("function test! ", this, "\t\t", _this);
}
}
}
运行结果为:
前者是真正的thisObj, 后者是传递的thisObj
function test! [object FunctionTest] [object FunctionTest]
function test! [object FunctionTest] [object FunctionTest]
function test! [object FunctionTest] [object Object]
function test! [object FunctionTest] [object Object]
function test! [object FunctionTest] null
function test! [object FunctionTest] null
function foo! [object FunctionTest] [object FunctionTest]
function foo! [object FunctionTest] [object FunctionTest]
function foo! [object Object] [object Object]
function foo! [object Object] [object Object]
function foo! [object global] null
function foo! [object global] null
» 转载请注明来源:www.litefeel.com » 《Function 指定thisObj》
» 本文链接地址:https://www.litefeel.com/function-modify-thisobj/
» 订阅本站:www.litefeel.com/feed/
» Host on Linode VPS
» 本文链接地址:https://www.litefeel.com/function-modify-thisobj/
» 订阅本站:www.litefeel.com/feed/
» Host on Linode VPS
This post was last modified on 2019 年 03 月 04 日 01:22
View Comments (1)
Many thanks for this article! Nevertheless, I experienced a difficult time viewing this article in Firefox. Just needed to convey that for your consideration! Thank you.