20,741
edits
mNo edit summary |
|||
Line 402: | Line 402: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
On the other hand, we were just about to make construction of such hashes much simpler. | On the other hand, we were just about to make construction of such hashes much simpler. This can be done by creating a new function that constructs hashes dynamically using a hash: | ||
<syntaxhighlight lang="php"> | <syntaxhighlight lang="php"> | ||
var | |||
var make_waypoint = func { | |||
return { parents:[waypoint] }; | |||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
Next, we are going to change the function and and embed it into the hash, so that the constructor function becomes a part of the class, renaming it to "new": | |||
<syntaxhighlight lang="php"> | <syntaxhighlight lang="php"> | ||
Line 443: | Line 435: | ||
var wp = waypoint.new(); | var wp = waypoint.new(); | ||
</syntaxhighlight> | </syntaxhighlight> | ||
Sometimes, you'll work with classes that do not have any custom constructor functions - but you can easily create a generic constructor, too: | |||
<syntaxhighlight lang="php"> | |||
var new = func { | |||
var t=[]; | |||
foreach(var a; args) append(t,a); | |||
return {parents:t}; | |||
} | |||
var Position3D = {x:0.0, y:0.0, z:0.0}; | |||
var p = new( Position3D ); | |||
</syntaxhighlight> | |||
You could even implement an overloaded function that creates arrays of objects. | |||
Now, let's imagine you want to add another member function to print a certain field's value, such as "number". This can be accomplished using the "me" keyword which ensures that the member function is always referring to the active object: | Now, let's imagine you want to add another member function to print a certain field's value, such as "number". This can be accomplished using the "me" keyword which ensures that the member function is always referring to the active object: |