Application Development Tips and Tricks > Coding conventions > Using prototypes when creating objects |
![]() ![]() ![]() |
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; }
The following example demonstrates a correct technique for creating an object, but should be used only when you want properties of the object to be instance-based rather than prototype-based:
// Less desirable practice for creating an object MyObject = function() { this.name = ""; this.setName = function(name) { this.name = name; } this.getName = function() { return this.name; } }
In the first example, each instance of MyObject
points to the same functions and properties defined in the object's prototype. Note, for instance, that only one copy of getName
exists in memory, regardless of the number of MyObject
objects created.
In the second example, each instance of MyObject
created makes a copy of each property and function. These extra property and function copies use additional memory, and in most cases, do not provide any advantages.
![]() ![]() ![]() |