Javascript: Object or Object.prototype?

痞子三分冷 提交于 2020-01-05 03:10:07

问题


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

回答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 */ };
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).



回答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.



来源:https://stackoverflow.com/questions/31275971/javascript-object-or-object-prototype

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!