Function 指定thisObj

发表评论 阅读评论

函数里可以使用this关键字,可以很方便的引用一个对象。

一般函数的 this 可以通过function.applyfunction.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
标签: , , , ,

  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.

  2. I do not know whether it's just me or if everyone
    else experiencing problems with your site. It appears like
    some of the written text on your posts are running off the screen. Can somebody else please
    provide feedback and let me know if this is happening to them too?
    This could be a issue with my web browser because I've had this happen previously.
    Appreciate it

  1. 本文目前尚无任何 trackbacks 和 pingbacks.
回到顶部