
Chapter 466
This code outputs:
7
7
0
1
2
3
4
5
In this case, the counter variable on the main Timeline is overwritten by the counter variable
within the function. Below is the corrected code, which uses the keyword
counter to declare
both of the variables. Using the counter declaration in the function fixes the bug in the code
above.
var counter = 7;
function loopTest()
{
trace(counter);
for(var counter = 0; counter < 5; counter++)
{
trace(counter);
}
}
trace(counter);
loopTest();
trace(counter);
Using prototypes when creating objects
When creating objects, attach object functions and properties that will be shared across all
instances of the object to the prototype of the object. This ensures that only one copy of each
function exists within memory. As a general rule, do not define functions within the constructor.
This creates a separate copy of the same function for each object instance and unnecessarily wastes
memory. This following example is the best practice for creating an object:
// Best practice for creating an object
MyObject = function()
{
}
MyObject.prototype.name = "";
MyObject.prototype.setName = function(name)
{
this.name = name;
}
MyObject.prototype.getName = function()
{
return this.name;
}
Commentaires sur ces manuels