markdown JS:Class&Prototypal Inheritance

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown JS:Class&Prototypal Inheritance相关的知识,希望对你有一定的参考价值。

## What’s the Difference Between Class & Prototypal Inheritance?

**Class Inheritance:** A class is like a blueprint — a description of the object to be created. Classes inherit from classes and create subclass relationships: hierarchical class taxonomies.
**Prototypal Inheritance**: A prototype is a working object instance. Objects inherit directly from other objects.

## When is prototypal inheritance an appropriate choice?
There is more than one type of prototypal inheritance:

- **Delegation** (i.e., the prototype chain).
- **Concatenative **(i.e. mixins, `Object.assign()`).
- **Functional** (Not to be confused with functional programming. A function used to create a closure for private state/encapsulation).
Each type of prototypal inheritance has its own set of use-cases, but all of them are equally useful in their ability to enable composition, which creates has-a or uses-a or can-do relationships as opposed to the is-a relationship created with class inheritance.

**Good to hear:**
- In situations where modules or functional programming don’t provide an obvious solution.
- When you need to compose objects from multiple sources.
- Any time you need inheritance.

**Red flags:**
- No knowledge of when to use prototypes.
- No awareness of mixins or `Object.assign()`.

The gist: class inheritance as it exists in Java does not exist in JavaScript, but JavaScript’s powerful combination of delegate prototypes and dynamic object extension allow you to reproduce most of the features of class inheritance from Java (with the notable exception of creating a static type).

Unfortunately, doing so also faithfully reprodeuces all of the problems caused by class inheritance.

JavaScript makes it trivially easy to favor composition instead: build objects from smaller component parts rather than inherit features from a single ancestor taxonomy.

In other words, `extends` should be avoided whenever it’s practical to do so, and people building classes should consider wrapping them in a factory rather than exporting the class to avoid encouraging class inheritance.

以上是关于markdown JS:Class&Prototypal Inheritance的主要内容,如果未能解决你的问题,请参考以下文章

markdown Cacher Pro Tips

markdown Cacher Pro Tips

markdown Cacher Pro Tips

markdown Cacher Pro Tips

markdown Cacher Pro Tips

markdown Cacher Pro Tips