Skip to content Skip to sidebar Skip to footer

Javascript: Object Or Object.prototype?

I just learned about prototype in Javascript (not the framework, the native feature). I perfectly got, at least one of its use. Example: Array.prototype.myMethod = function(){ /

Solution 1:

Why not use prototype?

Because if prototype is used then the subClass method is only available on instances of an Object. For example, to call subClass the following would be necessary:

Object.prototype.subClass = function(hash) { /* return an extended object that inherits Object's attributes */ };
functionMyClass() { };

var myInstance = newMyClass();
var mySubClassInstance = myInstance.subClass(); // only accessible on instances

This doesn't make much sense because the author wants subClass to return an extended instance of the object. The intent is not to create an instance of the parent "class" and then return a new sub instance from that instance. That's unnecessary.

By defining it right on Object, the subClass instance can be created without first creating an instance of MyClass:

Object.subClass = function(hash) { /* return an extended object that inherits Object's attributes */ };
functionMyClass() { };

var mySubClassInstance = MyClass.subClass();

Isn't more risky to add methods directly to the object rather than the prototype attached to it? Are there situations in which I'd prefer one way over the other.

  • Add to prototype to add members to instances of that object.
  • Add to the object to add members to that object (similar to the idea of static members).

Solution 2:

If you want method to be able to access class instance (with this keyword), use prototype. If you don't need this, declare function as member of class itself, so that you can call it without object.

Post a Comment for "Javascript: Object Or Object.prototype?"