83

Understanding JavaScript’s Prototypal Inheritance

 5 years ago
source link: https://www.tuicool.com/articles/hit/NZvAJbV
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

You might have heard people say that “In JavaScript, Everything is an Object” .

If you are not familiar with what an object looks like, here is an example:

QNRzM3B.png!web

While this is not entirely true in every case, people still consider the above statement to be true because JavaScript is a prototype-based Object Oriented Programming Language, instead of class-based .

In JavaScript, there are two main types of values:

  • Primitives — Strings, Numbers, Booleans, Undefined, and Null.
  • Objects — Arrays, Functions, Dates

So, while everything in JavaScript is not an object, the not-object things get wrapped into an object while compilation, allowing JavaScript to do really complicated operations. Even if you think that a value in your code is not an object, chances are that JavaScript has wrapped it inside one.

For example, if we create an empty function named hero :

function hero() {}

And like I mentioned before, functions are also classed as objects in JavaScript. So if we add a property type to this function and print it out, you will see that hero function is now also an object.

function hero() {}
hero.type = 'superman'
console.log(hero)
//Output
{ [Function: hero] type: 'superman' }

This is one of many things that makes JavaScript so awesome! :raised_hands:

To understand what Prototypal Inheritance is, we first need to understand what an Object Oriented Language is.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK