Instance vs class methods in JavaScript Part III
In prototype.js, it is possible to create class methods, which are generic. In the previous articles, class instances & instance methods can be called by using the 'new' keyword. Every class instance is encapsulated to prevent data from being overwritten when multiple classes, referencing the same class name, are instantiated on the same page. In a sense, a class instance is sandboxed. It has no awareness of other instances that reference the same class. When a subclass is instantiated, the superclass is also instantiated, protecting all superclass properties.
Class methods, on the other hand, behave like normal functions. Because class methods have no access to the 'this' scope, data cannot be persisted. Class methods are called directly, using the class name, followed by a function call.
Class instances & instance methods can take full advantage of an object orientated framework, but this can have implications for memory usage, if too many instances are created. So, care needs to be taken, to ensure that system design limits the amount of objects that can be instantiated, at any one time. Using class methods when appropriate can help to manage memory constraints.
Bird = Class.create (Abstract, { initialize: function (name) { this.name = name; }, //constructor method say: function (message) { return this.name + " says: " + message; } //public instance method }); Owl = Class.create (Bird, { say: function ($super, message) { return $super(message) + ", tweet"; } //public instance method }) Owl.activity = function(name,activity){ return name + " likes " + activity; } //public class method Owl.addMethods({ sleep: function(message) { return this.name + " says: " + message; } //public instance method }); var bird = new Bird("Robin"); //instantiate console.log(bird.say("tweet")); //public instance method call var owl = new Owl("Barnie"); //instantiate console.log(owl.say("hoot")); //public instance method call inherit & add console.log(Owl.activity(owl.name,"flying")); //public class method call console.log(owl.sleep("zzz")); //public instance method call add












