What techniques can be used to define a class in JavaScript, and what are their trade-offs?

后端 未结 19 1674
庸人自扰
庸人自扰 2020-11-22 07:26

I prefer to use OOP in large scale projects like the one I\'m working on right now. I need to create several classes in JavaScript but, if I\'m not mistaken, there are at le

19条回答
  •  温柔的废话
    2020-11-22 07:57

    The best way to define a class in JavaScript is to not define a class.

    Seriously.

    There are several different flavors of object-orientation, some of them are:

    • class-based OO (first introduced by Smalltalk)
    • prototype-based OO (first introduced by Self)
    • multimethod-based OO (first introduced by CommonLoops, I think)
    • predicate-based OO (no idea)

    And probably others I don't know about.

    JavaScript implements prototype-based OO. In prototype-based OO, new objects are created by copying other objects (instead of being instantiated from a class template) and methods live directly in objects instead of in classes. Inheritance is done via delegation: if an object doesn't have a method or property, it is looked up on its prototype(s) (i.e. the object it was cloned from), then the prototype's prototypes and so on.

    In other words: there are no classes.

    JavaScript actually has a nice tweak of that model: constructors. Not only can you create objects by copying existing ones, you can also construct them "out of thin air", so to speak. If you call a function with the new keyword, that function becomes a constructor and the this keyword will not point to the current object but instead to a newly created "empty" one. So, you can configure an object any way you like. In that way, JavaScript constructors can take on one of the roles of classes in traditional class-based OO: serving as a template or blueprint for new objects.

    Now, JavaScript is a very powerful language, so it is quite easy to implement a class-based OO system within JavaScript if you want to. However, you should only do this if you really have a need for it and not just because that's the way Java does it.

提交回复
热议问题