0

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?

2
  • Neither; the first form does not use JavaScript's prototypal inheritance, the second form creates a new closure for each object instance. Commented Oct 26, 2011 at 5:35
  • I strongly suggest you to read through the accepted answer on this SO question. Commented Oct 26, 2011 at 5:44

2 Answers 2

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());
Sign up to request clarification or add additional context in comments.

2 Comments

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.
@Guffa I would also recommend that you at least mention of global namepspace/variable pollution danger that comes with your method.
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.