Skip to content

Instantly share code, notes, and snippets.

View amerrika's full-sized avatar

Amer Tričić amerrika

View GitHub Profile
@amerrika
amerrika / 3. Practicing.md
Last active April 13, 2024 12:24
Practicing prototypes and inheritance with our own examples.

Prototypes and Inheritance Exercise

After going through first two articles, Prototypes and Inheritance, it's time to do some practice and keep learning through doing. The example I came up with for this article is for learning purposes. It's not related to real-world use cases.

Thinking of a good example turned out to be tricky. One of the reasons for that is a difficulty of coming up with an example that has some kind of meaningful logic and hierarchy. Hopefully my solution will do the job.

Explaining Our Case

The idea is the following:

  • we need to create some kind of task items (as in todo projects). Let's say, they represent <li> elements in a way.
  • now, we'll assume that there are two types of these items based on their priority: primary and secondary.
  • further, let's assume that all task items have the same parent element (ul) and the same css class. One p

Inheritance

After grasping the concept of prototype objects in the first article (Prototypes) , we are going to focus on the inheritance. Without going too deep and covering all aspects this article should answer following questions:

  • How inheritance works
  • Why it is an important concept in JavaScript and
  • Why it is useful for us to understand it

Prototypal Inheritance

This kind of inheritance is based on the prototype chain. A prototype object is just that: a regular object. This is way it's necessary to have some kind of mechanism that makes it possible for created objects to inherit methods and properties. We have already mentioned this mechanism briefly in our Prototypes article. It is generally called internal prototype (historically _proto_ but the use of it has been deprecated).

@amerrika
amerrika / Prototypes.md
Last active April 7, 2024 08:56
JavaScript Prototype

Prototypes

Prototypes are the mechanism by which JavaScript objects inherit methods and properties from one another. Prototypes are important part of JavaScript and therefore it's important to understand the basics of this concept.

The goal of this article is to show how prototype object of constructor functions is used to pass methods and properties to its instances.

Prototype as a Property of Functions

In JavaScript, functions are objects. They are instances of the Function() constructor and this way every created function inherit certain methods and properties. One such inherited property is prototype. Initial value of the prototype is an empty object. Arrow functions are an exception, they do not have the prototype object and cannot be used as a constructor.

Let's create a simple function and we'll see that by default it contains the prototype property