ActionScript 3 Language Specification |
|||
| ActionScript 3.0 Language Specification > 8 Functions > 8.3 Function objects | |||
Global and nested functions can be used as constructors in instantiation expressions, as shown in the following example:
function A() { this.x = 10 }
var o = new A
trace(o.x) // traces 10
Function objects have a property named prototype whose value is used to initialize the intrinsic delegate property of the objects it creates. The prototype property has a default value of a new instance of the class Object. Building on the previous example:
function A() { this.x = 10 }
function B() {}
B.prototype = new A
var o = new B
trace(o.x) // traces 10
The value of o is an instance of B, which delegates to an instance of A, which has a property named x with value of 10.
Constructor methods inside of a class are also used to create objects. But, unlike constructor functions, constructor methods create objects with a set of fixed properties (traits) associated with its class and a delegate that is also an instance of its class.
class A {
var x
function A() { this.x = 10 }
}
var o = new A
trace(o.x) // traces 10
There are some subtle differences between the preceding example and the one involving a function constructor:
x is a fixed property of each instance of A rather than a dynamic property.A.prototype is an instance of A rather than an instance of Object.A(expr) does not call the function A defined in class A. It results in an explicit conversion of the value of expr to the type A.Class methods are functions that are defined with the static attribute inside of a class definition. A class method cannot be used as a constructor and does not define the this reference. Class methods are in the scope of the class object in which they are defined.
Instance methods are functions that are defined without the static attribute and inside a class definition. Instance methods are associated with an instance of the class in which they are defined. Instance methods can override or implement inherited class or interface methods and always have a value bound to this.
The value of this in an instance method is the value of the instance the method belongs to. When an instance method is extracted from an object, a bound method is created to bind the value of this to that host object. Assignment of the bound method to a property of another object does not affect the binding of this. For example:
class A {
var x
function A() { this.x = 10 }
function m() { trace(this.x) }
}
var a = new A()
var o = { x : 20 }
o.m = a.m
o.m() // traces 10
RSS feed | Send me an e-mail when comments are added to this page | Comment Report
Current page: http://livedocs.adobe.com/specs/actionscript/3/as3_specification68.html
Comments
Joe@emeraldforest said on Feb 22, 2008 at 2:34 PM :