Constructors and prototypes
From Yate Documentation
(Difference between revisions)
(Created page with " The Javascript language does not have classes, it supports only objects. However, a common behavior of objects can be implemented using prototypes. ===Adding class propertie...") |
|||
Line 16: | Line 16: | ||
MyConstructor.prototype = new Object; | MyConstructor.prototype = new Object; | ||
</pre> | </pre> | ||
+ | |||
Now shared properties and methods can be added to the prototype: | Now shared properties and methods can be added to the prototype: | ||
+ | |||
<pre> | <pre> | ||
MyConstructor.prototype.SharedProperty = 1; | MyConstructor.prototype.SharedProperty = 1; | ||
Line 27: | Line 29: | ||
'''IMPORTANT:''' There's a semicolon after the closing brace as this is an assignment and not a function declaration | '''IMPORTANT:''' There's a semicolon after the closing brace as this is an assignment and not a function declaration | ||
+ | ===Accessing the prototype=== | ||
+ | |||
+ | Javascript does not provide a standard way of accessing an object's prototype. | ||
+ | |||
+ | Yate uses a widespread extension of an '''__proto__''' attribute to access the prototype: | ||
+ | |||
+ | <pre> | ||
+ | Engine.print_r(this.__proto__); | ||
+ | </pre> | ||
'''See also''' | '''See also''' |
Revision as of 20:43, 6 February 2013
The Javascript language does not have classes, it supports only objects. However, a common behavior of objects can be implemented using prototypes.
Adding class properties and methods
Even if objects are not class members they can share a set of common properties and methods.
Currently Yate does not automatically provide a prototype for objects. This can be added easily to a constructor:
function MyConstructor() { this.MyProperty = 0; } MyConstructor.prototype = new Object;
Now shared properties and methods can be added to the prototype:
MyConstructor.prototype.SharedProperty = 1; MyConstructor.prototype.MyMethod = function(x) { return x + this.MyProperty; };
IMPORTANT: There's a semicolon after the closing brace as this is an assignment and not a function declaration
Accessing the prototype
Javascript does not provide a standard way of accessing an object's prototype.
Yate uses a widespread extension of an __proto__ attribute to access the prototype:
Engine.print_r(this.__proto__);
See also
External links