1

I want to do a framework (academically) animations in JavaScript and Canvas, I began to look for guides DONE of object-oriented programming with javascript and I find too many variations.

examples:

// Example 1
var object = {
  public_method: function(){ //do something }
}

// Example 2
function object(){
  this.public_method = function(){ //do something }
}
var o = new object();

which is the correct or best way (simple and light) to do so.

note: that good design pattern for this kind of project?

rkmax
  • 17,633
  • 23
  • 91
  • 176
  • Neither; the first form does not use JavaScript's prototypal inheritance, the second form creates a new closure for each object instance. – Phrogz Oct 26 '11 at 05:35
  • I strongly suggest you to read through the accepted answer on [this](http://stackoverflow.com/questions/1595611/how-to-properly-create-a-custom-object-in-javascript) SO question. – ZenMaster Oct 26 '11 at 05:44

2 Answers2

4

The first will only create one single instance, while the second can be used to create several instances.

I prefer using a constructor function and putting the methods in the prototype. That way the methods are created once for all instances instead of created separately for each instance:

function ExampleObject() {
  this.answer = 42;
}

ExampleObject.prototype = {
  get_answer: function(){ return this.answer; },
  another_method: function(){}
};

var obj = new ExampleObject();
alert(obj.get_answer());
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • 1
    Recommend that you clarify the difference between setting functions in the prototype versus creating closures for each object instance in the 'constructor'. Also strongly recommend you use something other than `Object` in your example. – Phrogz Oct 26 '11 at 05:34
  • @Guffa I would also recommend that you at least mention of global namepspace/variable pollution danger that comes with your method. – ZenMaster Oct 26 '11 at 05:45
3

If you want something that will be similar to the classic OOP design (which revolves around classes), you should do something like this:

function MyClass(param1, param2) {
    this.param1 = param1;
    this.param2 = param2; // These are fields.
}
MyClass.prototype.publicMethod = function() {
    // do something
}
var o = new MyClass(x, y);

I suggest you read more about prototype. This enables you creating many instances of the same "class", without wasting memory, execution and programming defining the methods for each instance separately.

Tom
  • 4,910
  • 5
  • 33
  • 48