2

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(){
   /*do something super awesome*/
}
var a = [];
a.myMethod();

Reading on I came upon an example in which the author adds a subClass method to the Object object, by doing this:

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

The goal is to create a method that resembles a more object-oriented language syntax. Since I expected the book author to define such method using the prototype feature my question is:

  • Why not use prototype?
  • 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

2 Answers 2

3

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 */ };
function MyClass() { };

var myInstance = new MyClass();
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 */ };
function MyClass() { };

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

1 Comment

Perfectly clear explanation, and actually pretty obvious looking back. Thank you very much!
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.