function MyObject(title){ this.title = title; this.test = function() { console.log('test from ' + this.title); console.log(this.staticItemsMember.join(' - ')); } } MyObject.prototype = { staticItemsMember : [1, 2, 3], addItems : function(items) { var title = this.title || 'was called from constructor method', i = 0, l; console.log('add items in function of class instance (' + title + ')'); if (!(items instanceof Array)) { items = [items]; } for (l = items.length; i < l; i++) { this.staticItemsMember.push(items[i]); } } } MyObject.addItems = function(items) { console.log('add items in function of class constructor'); this.prototype.addItems(items); } var o = new MyObject('o'); o.test(); MyObject.addItems([5, 6]); o.test(); o.addItems([8, 9, 10]); o.test(); MyObject.addItems(11); o.test(); var m = new MyObject('m'); m.test(); m.addItems([12, 13]); o.test(); m.test(); MyObject.addItems([14, 15, 16, 17]); m.test(); o.test(); o.addItems([18, 19, 20]); m.test(); o.test();
This will output in browser's console text like:
>>> function MyObject(title){ this.title = title...); o.addItems([18, 19, 20]); m.test(); o.test(); test from o 1 - 2 - 3 add items in function of class constructor add items in function of class instance (was called from constructor method) test from o 1 - 2 - 3 - 5 - 6 add items in function of class instance (o) test from o 1 - 2 - 3 - 5 - 6 - 8 - 9 - 10 add items in function of class constructor add items in function of class instance (was called from constructor method) test from o 1 - 2 - 3 - 5 - 6 - 8 - 9 - 10 - 11 test from m 1 - 2 - 3 - 5 - 6 - 8 - 9 - 10 - 11 add items in function of class instance (m) test from o 1 - 2 - 3 - 5 - 6 - 8 - 9 - 10 - 11 - 12 - 13 test from m 1 - 2 - 3 - 5 - 6 - 8 - 9 - 10 - 11 - 12 - 13 add items in function of class constructor add items in function of class instance (was called from constructor method) test from m 1 - 2 - 3 - 5 - 6 - 8 - 9 - 10 - 11 - 12 - 13 - 14 - 15 - 16 - 17 test from o 1 - 2 - 3 - 5 - 6 - 8 - 9 - 10 - 11 - 12 - 13 - 14 - 15 - 16 - 17 add items in function of class instance (o) test from m 1 - 2 - 3 - 5 - 6 - 8 - 9 - 10 - 11 - 12 - 13 - 14 - 15 - 16 - 17 - 18 - 19 - 20 test from o 1 - 2 - 3 - 5 - 6 - 8 - 9 - 10 - 11 - 12 - 13 - 14 - 15 - 16 - 17 - 18 - 19 - 20