Kevin Li
Kevin Li

Reputation: 1538

Extending Object prototype in ActionScript 3

Whenever I try to extend the Object prototype, I get an error:

Error #1056: Cannot create property my_extension on mx.core.UIComponentDescriptor.

I searched around, and found these:

Flash AS3: ReferenceError: Error #1056: Cannot create property

ReferenceError: Error #1056 - instance name Error

I'm not using a visual IDE for designing a stage, but MXML and AS3 files, so I'm not sure what to make of this error.

My code:

Object.prototype.keys = function(): Array {
  var keys: Array = [];

  for (var key: * in this) {
    keys.push(key);
  }

  return keys;
}

Object.prototype.values = function(): Array {
  var values: Array = [];

  for each (var value: * in this) {
    values.push(value);
  }

  return values;
}

Upvotes: 1

Views: 2209

Answers (1)

Jason Sturges
Jason Sturges

Reputation: 15955

Using prototype to extend a class seems very ActionScript 1 or 2.

In AS3, you may be able to prototype if the class is dynamic.

There are downsides to prototype:

  • Only dynamic classes can be extended, one can not add methods to Math for example.
  • Calls to methods stored in the prototype take longer to execute.
  • Since methods are added at run-time, editors can not show them with code hinting or use the correct syntax highlighting.

Since all classes extend object, it is not necessary to explicitly declare Object as a base; however, you could define an AbstractObject class to be extended:

package
{

    public dynamic class AbstractObject extends Object
    {

        public function AbstractObject()
        {
            super();
        }

        public function get keys():Array
        {
            var keys:Array = [];

            for (var key:* in this)
            {
                keys.push(key);
            }

            return keys;
        }

        public function get values():Array
        {
            var values:Array = [];

            for each (var value:* in this)
            {
                values.push(value);
            }

            return values;
        }

    }
}

Subtype AbstractObject for your classes.

Upvotes: 4

Related Questions