Understanding OOP in ActionScript

A.as : 

    public class A {

    public function getFunction():Function { 
      return function():void {
        if(this is C) {
          trace("C");
        } else {
          trace("not C");
        }
     }
  }


public function func1():void {
   var internalFunc:Function = getFunction();
   internalFunc();
 }

}

B.as : 
public class B extends A implements C {

}

In another class:

var b:B = new B();
   B.func1();

Output: "Not C"

I expected the trace output to be "C"

Can someone explain why?

+3
source share
2 answers

An anonymous function , if called directly, is bound to a global object. If you trace thisinside it, you will see [object global]instead [object B]what it would be if it applies to b.

A common workaround is to use a closure:

  var self:A = this;
  return function():void {
    if(self is C) {
      trace("C");
    } else {
      trace("not C");
    }
 }

, , , , . , .

Amarghosh:

, this , , . :

package  {
 import flash.display.Sprite;
 public class Test extends Sprite {
  private var foo:String = "foo";
  public function Test() {
   var anonymous:Function = function ():void {
    trace(foo);//foo
    trace(this.foo);//undefined
   };
   anonymous();
  } 
 }
}

Greetz
back2dos

+5

, , ?

getFunction() , , .
func1() , B. . , .

, . - C. - . A:

    public function getFunction():Function { 
        if(this is C) {
            trace("C");
        } else {
            trace("not C");
        }
        return getFunction;
    }

, createComplete MXML:

            var b:B = new B();
            b.func1();

, " " , , - .

+1

Source: https://habr.com/ru/post/1754818/


All Articles