Reputation: 759
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:
Upvotes: 2
Views: 89
Reputation: 106640
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.
Upvotes: 3
Reputation: 290
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.
Upvotes: 1