Javascript: Object or Object.prototype? -
i learned prototype in javascript (not framework, native feature). got, @ least 1 of use. example:
array.prototype.mymethod = function(){ /*do super awesome*/ } var = []; a.mymethod(); reading on came upon example in author adds subclass method object object, doing this:
object.subclass = function(hash){/*return extended object inherits object's attributes*/} the goal create method resembles more object-oriented language syntax. since expected book author define such method using prototype feature question is:
- why not use prototype?
- isn't more risky add methods directly object rather prototype attached it?
- are there situations in i'd prefer 1 way on other
why not use prototype?
because if prototype used subclass method available on instances of object. example, call subclass following necessary:
object.prototype.subclass = function(hash) { /* return extended object inherits object's attributes */ }; function myclass() { }; var myinstance = new myclass(); var mysubclassinstance = myinstance.subclass(); // accessible on instances this doesn't make sense because author wants subclass return extended instance of object. intent not create instance of parent "class" , return new sub instance instance. that's unnecessary.
by defining right on object, subclass instance can created without first creating instance of myclass:
object.subclass = function(hash) { /* return extended object inherits object's attributes */ }; function myclass() { }; var mysubclassinstance = myclass.subclass(); isn't more risky add methods directly object rather prototype attached it? there situations in i'd prefer 1 way on other.
- add prototype add members instances of object.
- add object add members object (similar idea of static members).
Comments
Post a Comment