JavaScript is a prototype-based OO language. Search on Google for the "Self" programming language for more info on this concept since it is the pioneer in this type of OO.

Brian Feliciano wrote:
is there a difference between:

var ObjectName = Class.create();
ObjectName.prototype = {
  initialize: function () {},
  doThis: function () {}
}
var obj = new ObjectName();
obj.doThis();

In this case you are creating a prototype object (located at ObjectName.prototype) and defining a constructor function which will spawn a new object from that prototype object, executing that constructor function to create your new object then executing a method on that new object. You can think of this as somewhat like doing the following (it is a bit different but I'm trying to keep just the core concepts here):

ObjectName.prototype = {
  initialize: function () {},
  doThis: function () {}
}
var obj = new Object();
obj.prototype = ObjectName.prototype;
obj.initialize();
obj.doThis();

What Prototype is trying to do here is trying to simulate class-based OO on top of the built-in prototype-based OO. The idea is to treat the object "ObjectName" as the class (and methods defined on this object would be considered class methods). Instance methods are defined on "ObjectName.prototype". "initialize" is your constructor for creating new instances of your class. The goals is to make JavaScript more comfortable to developers who are used to class-based OO that most OO languages implement (Ruby, C#, Java, etc.)

var ObjectName = {
  initialize: function () {},
  doThis: function () {}
}
ObjectName.doThis();

This on the other hand is just using normal prototype-based OO. Here you are creating an object literal (the stuff inside the {}) with your methods defined and assigning that object literal to the identifier "ObjectName". You are this using that object as a normal instance without worrying about defining abstract concepts like classes.

It is important to note that your "initialize" method is not automatically executed for you. That is something that prototype does for you when you execute "Class.create()" (it defines a constructor function which will execute "initialize" on the new instance being created). No constructor is run when using an object literal. Only if you define a constructor function and create new instances from the constructor function's prototype object is a constructor executed.

Eric

_______________________________________________
Rails-spinoffs mailing list
Rails-spinoffs@lists.rubyonrails.org
http://lists.rubyonrails.org/mailman/listinfo/rails-spinoffs

Reply via email to