You can see from the answers that you already have several ways.
#1 var o = new Object(); o.method = function(){} #2 var o = new Object(); o.prototype.method = function(){} #3 function myObject() { this.method = function(){} } var o = new myObject(); #4 function myObject() {} myObject.prototype.method = function(){} var o = new myObject(); #5 var o = { method: function(){} }
# 3 and # 4 use the constructor function. this means that you can use them to create multiple objects of the same class (classes don't actually exist in JavaScript)
# 4 is different from # 3 because all the objects built by C # 4 will share the method, since it is a property of their prototype. This saves memory (but only a very small amount), and if you change the prototype method, all # 4 objects will be updated immediately - even if they have already been created.
# 1, # 2 and # 5 are all pretty much equivalent. This is due to the fact that maybe someday there will be only one of them at a time, so the fact that No. 2 has a method added to the prototype does not really matter. (excluding cloning)
There are several more ways to add methods to objects using factories with closure or add βstaticβ properties / methods to functions or private nested functions ... :)
meouw Feb 02 '09 at 21:04 2009-02-02 21:04
source share