Riley Lambert

Riley Lambert

1558601137

A Beginner's Guide to Prototypes and Inheritance in JavaScript

In this tutorial, we will learn what object prototypes are, understanding prototypes and inheritance in JavaScript, how to use the constructor function to extend prototypes into new objects. We will also learn about inheritance and the prototype chain.

Introduction

JavaScript is a prototype-based language, meaning object properties and methods can be shared through generalized objects that have the ability to be cloned and extended. This is known as prototypical inheritance and differs from class inheritance. Among popular object-oriented programming languages, JavaScript is relatively unique, as other prominent languages such as PHP, Python, and Java are class-based languages, which instead define classes as blueprints for objects.

In this tutorial, we will learn what object prototypes are and how to use the constructor function to extend prototypes into new objects. We will also learn about inheritance and the prototype chain.

JavaScript Prototypes

In Understanding Objects in JavaScript, we went over the object data type, how to create an object, and how to access and modify object properties. Now we will learn how prototypes can be used to extend objects.

Every object in JavaScript has an internal property called [[Prototype]]. We can demonstrate this by creating a new, empty object.

let x = {};

This is the way we would normally create an object, but note that another way to accomplish this is with the object constructor: let x = new Object().

The double square brackets that enclose [[Prototype]] signify that it is an internal property, and cannot be accessed directly in code.

To find the [[Prototype]] of this newly created object, we will use the getPrototypeOf() method.

Object.getPrototypeOf(x);

The output will consist of several built-in properties and methods.

{constructor: ƒ, __defineGetter__: ƒ, __defineSetter__: ƒ, …}

Another way to find the [[Prototype]] is through the __proto__ property. [__proto__](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto) is a property that exposes the internal [[Prototype]] of an object.

It is important to note that .__proto__ is a legacy feature and should not be used in production code, and it is not present in every modern browser. However, we can use it throughout this article for demonstrative purposes.

x.__proto__;

The output will be the same as if you had used getPrototypeOf().

{constructor: ƒ, __defineGetter__: ƒ, __defineSetter__: ƒ, …}

It is important that every object in JavaScript has a [[Prototype]] as it creates a way for any two or more objects to be linked.

Objects that you create have a [[Prototype]], as do built-in objects, such as Date and Array. A reference can be made to this internal property from one object to another via the prototype property, as we will see later in this tutorial.

Prototype Inheritance

When you attempt to access a property or method of an object, JavaScript will first search on the object itself, and if it is not found, it will search the object’s [[Prototype]]. If after consulting both the object and its [[Prototype]] still no match is found, JavaScript will check the prototype of the linked object, and continue searching until the end of the prototype chain is reached.

At the end of the prototype chain is [Object.prototype](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype). All objects inherit the properties and methods of [Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object). Any attempt to search beyond the end of the chain results in null.

In our example, x is an empty object that inherits from Object. x can use any property or method that Object has, such as toString().

x.toString();
[object Object]

This prototype chain is only one link long. x -> Object. We know this, because if we try to chain two [[Prototype]] properties together, it will be null.

x.__proto__.__proto__;
null

Let’s look at another type of object. If you have experience Working with Arrays in JavaScript, you know they have many built-in methods, such as pop() and push(). The reason you have access to these methods when you create a new array is because any array you create has access to the properties and methods on the Array.prototype.

We can test this by creating a new array.

let y = [];

Keep in mind that we could also write it as an array constructor, let y = new Array().

If we take a look at the [[Prototype]] of the new y array, we will see that it has more properties and methods than the x object. It has inherited everything from Array.prototype.

y.__proto__;
[constructor: ƒ, concat: ƒ, pop: ƒ, push: ƒ, …]

You will notice a constructor property on the prototype that is set to Array(). The constructor property returns the constructor function of an object, which is a mechanism used to construct objects from functions.

We can chain two prototypes together now, since our prototype chain is longer in this case. It looks like y -> Array -> Object.

y.__proto__.__proto__;
{constructor: ƒ, __defineGetter__: ƒ, __defineSetter__: ƒ, …}

This chain is now referring to Object.prototype. We can test the internal [[Prototype]] against the prototype property of the constructor function to see that they are referring to the same thing.

y.__proto__ === Array.prototype;            // true
y.__proto__.__proto__ === Object.prototype; // true

We can also use the isPrototypeOf() method to accomplish this.

Array.prototype.isPrototypeOf(y);      // true
Object.prototype.isPrototypeOf(Array); // true

We can use the instanceof operator to test whether the prototype property of a constructor appears anywhere within an object’s prototype chain.

y instanceof Array; // true

To summarize, all JavaScript objects have a hidden, internal [[Prototype]] property (which may be exposed through __proto__ in some browsers). Objects can be extended and will inherit the properties and methods on [[Prototype]] of their constructor.

These prototypes can be chained, and each additional object will inherit everything throughout the chain. The chain ends with the Object.prototype.

Constructor Functions

Constructor functions are functions that are used to construct new objects. The [new](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new) operator is used to create new instances based off a constructor function. We have seen some built-in JavaScript constructors, such as new Array() and new Date(), but we can also create our own custom templates from which to build new objects.

As an example, let’s say we are creating a very simple, text-based role-playing game. A user can select a character and then choose what character class they will have, such as warrior, healer, thief, and so on.

Since each character will share many characteristics, such as having a name, a level, and hit points, it makes sense to create a constructor as a template. However, since each character class may have vastly different abilities, we want to make sure each character only has access to their own abilities. Let’s take a look at how we can accomplish this with prototype inheritance and constructors.

To begin, a constructor function is just a regular function. It becomes a constructor when it is called on by an instance with the new keyword. In JavaScript, we capitalize the first letter of a constructor function by convention.

characterSelect.js

// Initialize a constructor function for a new Hero
function Hero(name, level) {
  this.name = name;
  this.level = level;
}

We have created a constructor function called Hero with two parameters: name and level. Since every character will have a name and a level, it makes sense for each new character to have these properties. The this keyword will refer to the new instance that is created, so setting this.name to the name parameter ensures the new object will have a name property set.

Now we can create a new instance with new.

let hero1 = new Hero('Bjorn', 1);

If we console out hero1, we will see a new object has been created with the new properties set as expected.

Hero {name: "Bjorn", level: 1}

Now if we get the [[Prototype]] of hero1, we will be able to see the constructor as Hero(). (Remember, this has the same input as hero1.__proto__, but is the proper method to use.)

Object.getPrototypeOf(hero1);
constructor: ƒ Hero(name, level)

You may notice that we’ve only defined properties and not methods in the constructor. It is a common practice in JavaScript to define methods on the prototype for increased efficiency and code readability.

We can add a method to Hero using prototype. We’ll create a greet() method.

characterSelect.js

...
// Add greet method to the Hero prototype
Hero.prototype.greet = function () {
  return `${this.name} says hello.`;
}

Since greet() is in the prototype of Hero, and hero1 is an instance of Hero, the method is available to hero1.

hero1.greet();
"Bjorn says hello."

If you inspect the [[Prototype]] of Hero, you will see greet() as an available option now.

This is good, but now we want to create character classes for the heroes to use. It wouldn’t make sense to put all the abilities for every class into the Hero constructor, because different classes will have different abilities. We want to create new constructor functions, but we also want them to be connected to the original Hero.

We can use the [call()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call) method to copy over properties from one constructor into another constructor. Let’s create a Warrior and a Healer constructor.

characterSelect.js

...
// Initialize Warrior constructor
function Warrior(name, level, weapon) {
  // Chain constructor with call
  Hero.call(this, name, level);

  // Add a new property
  this.weapon = weapon;
}

// Initialize Healer constructor
function Healer(name, level, spell) {
  Hero.call(this, name, level);

  this.spell = spell;
}

Both new constructors now have the properties of Hero and a few unqiue ones. We’ll add the attack() method to Warrior, and the heal() method to Healer.

characterSelect.js

...
Warrior.prototype.attack = function () {
  return `${this.name} attacks with the ${this.weapon}.`;
}

Healer.prototype.heal = function () {
  return `${this.name} casts ${this.spell}.`;
}

At this point, we’ll create our characters with the two new character classes available.

characterSelect.js

const hero1 = new Warrior('Bjorn', 1, 'axe');
const hero2 = new Healer('Kanin', 1, 'cure');

hero1 is now recognized as a Warrior with the new properties.

Warrior {name: "Bjorn", level: 1, weapon: "axe"}

We can use the new methods we set on the Warrior prototype.

hero1.attack();
"Bjorn attacks with the axe."

But what happens if we try to use methods further down the prototype chain?

hero1.greet();
Uncaught TypeError: hero1.greet is not a function

Prototype properties and methods are not automatically linked when you use call() to chain constructors. We will use Object.create() to link the prototypes, making sure to put it before any additional methods are created and added to the prototype.

characterSelect.js

...
Warrior.prototype = Object.create(Hero.prototype);
Healer.prototype = Object.create(Hero.prototype);

// All other prototype methods added below
...

Now we can successfully use prototype methods from Hero on an instance of a Warrior or Healer.

hero1.greet();
"Bjorn says hello."

Here is the full code for our character creation page.

characterSelect.js

// Initialize constructor functions
function Hero(name, level) {
  this.name = name;
  this.level = level;
}

function Warrior(name, level, weapon) {
  Hero.call(this, name, level);

  this.weapon = weapon;
}

function Healer(name, level, spell) {
  Hero.call(this, name, level);

  this.spell = spell;
}

// Link prototypes and add prototype methods
Warrior.prototype = Object.create(Hero.prototype);
Healer.prototype = Object.create(Hero.prototype);

Hero.prototype.greet = function () {
  return `${this.name} says hello.`;
}

Warrior.prototype.attack = function () {
  return `${this.name} attacks with the ${this.weapon}.`;
}

Healer.prototype.heal = function () {
  return `${this.name} casts ${this.spell}.`;
}

// Initialize individual character instances
const hero1 = new Warrior('Bjorn', 1, 'axe');
const hero2 = new Healer('Kanin', 1, 'cure');

With this code we’ve created our Hero class with the base properties, created two character classes called Warrior and Healer from the original constructor, added methods to the prototypes and created individual character instances.

Conclusion

JavaScript is a prototype-based language, and functions differently than the traditional class-based paradigm that many other object-oriented languages use.

In this tutorial, we learned how prototypes work in JavaScript, and how to link object properties and methods via the hidden [[Prototype]] property that all objects share. We also learned how to create custom constructor functions and how prototype inheritance works to pass down property and method values.

#javascript #web-development

What is GEEK

Buddha Community

A Beginner's Guide to Prototypes and Inheritance in JavaScript
Sival Alethea

Sival Alethea

1624298400

Learn JavaScript - Full Course for Beginners. DO NOT MISS!!!

This complete 134-part JavaScript tutorial for beginners will teach you everything you need to know to get started with the JavaScript programming language.
⭐️Course Contents⭐️
0:00:00 Introduction
0:01:24 Running JavaScript
0:04:23 Comment Your Code
0:05:56 Declare Variables
0:06:15 Storing Values with the Assignment Operator
0:11:31 Initializing Variables with the Assignment Operator
0:11:58 Uninitialized Variables
0:12:40 Case Sensitivity in Variables
0:14:05 Add Two Numbers
0:14:34 Subtract One Number from Another
0:14:52 Multiply Two Numbers
0:15:12 Dividing Numbers
0:15:30 Increment
0:15:58 Decrement
0:16:22 Decimal Numbers
0:16:48 Multiply Two Decimals
0:17:18 Divide Decimals
0:17:33 Finding a Remainder
0:18:22 Augmented Addition
0:19:22 Augmented Subtraction
0:20:18 Augmented Multiplication
0:20:51 Augmented Division
0:21:19 Declare String Variables
0:22:01 Escaping Literal Quotes
0:23:44 Quoting Strings with Single Quotes
0:25:18 Escape Sequences
0:26:46 Plus Operator
0:27:49 Plus Equals Operator
0:29:01 Constructing Strings with Variables
0:30:14 Appending Variables to Strings
0:31:11 Length of a String
0:32:01 Bracket Notation
0:33:27 Understand String Immutability
0:34:23 Find the Nth Character
0:34:51 Find the Last Character
0:35:48 Find the Nth-to-Last Character
0:36:28 Word Blanks
0:40:44 Arrays
0:41:43 Nest Arrays
0:42:33 Access Array Data
0:43:34 Modify Array Data
0:44:48 Access Multi-Dimensional Arrays
0:46:30 push()
0:47:29 pop()
0:48:33 shift()
0:49:23 unshift()
0:50:36 Shopping List
0:51:41 Write Reusable with Functions
0:53:41 Arguments
0:55:43 Global Scope
0:59:31 Local Scope
1:00:46 Global vs Local Scope in Functions
1:02:40 Return a Value from a Function
1:03:55 Undefined Value returned
1:04:52 Assignment with a Returned Value
1:05:52 Stand in Line
1:08:41 Boolean Values
1:09:24 If Statements
1:11:51 Equality Operator
1:13:18 Strict Equality Operator
1:14:43 Comparing different values
1:15:38 Inequality Operator
1:16:20 Strict Inequality Operator
1:17:05 Greater Than Operator
1:17:39 Greater Than Or Equal To Operator
1:18:09 Less Than Operator
1:18:44 Less Than Or Equal To Operator
1:19:17 And Operator
1:20:41 Or Operator
1:21:37 Else Statements
1:22:27 Else If Statements
1:23:30 Logical Order in If Else Statements
1:24:45 Chaining If Else Statements
1:27:45 Golf Code
1:32:15 Switch Statements
1:35:46 Default Option in Switch Statements
1:37:23 Identical Options in Switch Statements
1:39:20 Replacing If Else Chains with Switch
1:41:11 Returning Boolean Values from Functions
1:42:20 Return Early Pattern for Functions
1:43:38 Counting Cards
1:49:11 Build Objects
1:50:46 Dot Notation
1:51:33 Bracket Notation
1:52:47 Variables
1:53:34 Updating Object Properties
1:54:30 Add New Properties to Object
1:55:19 Delete Properties from Object
1:55:54 Objects for Lookups
1:57:43 Testing Objects for Properties
1:59:15 Manipulating Complex Objects
2:01:00 Nested Objects
2:01:53 Nested Arrays
2:03:06 Record Collection
2:10:15 While Loops
2:11:35 For Loops
2:13:56 Odd Numbers With a For Loop
2:15:28 Count Backwards With a For Loop
2:17:08 Iterate Through an Array with a For Loop
2:19:43 Nesting For Loops
2:22:45 Do…While Loops
2:24:12 Profile Lookup
2:28:18 Random Fractions
2:28:54 Random Whole Numbers
2:30:21 Random Whole Numbers within a Range
2:31:46 parseInt Function
2:32:36 parseInt Function with a Radix
2:33:29 Ternary Operator
2:34:57 Multiple Ternary Operators
2:36:57 var vs let
2:39:02 var vs let scopes
2:41:32 const Keyword
2:43:40 Mutate an Array Declared with const
2:44:52 Prevent Object Mutation
2:47:17 Arrow Functions
2:28:24 Arrow Functions with Parameters
2:49:27 Higher Order Arrow Functions
2:53:04 Default Parameters
2:54:00 Rest Operator
2:55:31 Spread Operator
2:57:18 Destructuring Assignment: Objects
3:00:18 Destructuring Assignment: Nested Objects
3:01:55 Destructuring Assignment: Arrays
3:03:40 Destructuring Assignment with Rest Operator to Reassign Array
3:05:05 Destructuring Assignment to Pass an Object
3:06:39 Template Literals
3:10:43 Simple Fields
3:12:24 Declarative Functions
3:12:56 class Syntax
3:15:11 getters and setters
3:20:25 import vs require
3:22:33 export
3:23:40 * to Import
3:24:50 export default
3:25:26 Import a Default Export
📺 The video in this post was made by freeCodeCamp.org
The origin of the article: https://www.youtube.com/watch?v=PkZNo7MFNFg&list=PLWKjhJtqVAblfum5WiQblKPwIbqYXkDoC&index=4

🔥 If you’re a beginner. I believe the article below will be useful to you ☞ What You Should Know Before Investing in Cryptocurrency - For Beginner
⭐ ⭐ ⭐The project is of interest to the community. Join to Get free ‘GEEK coin’ (GEEKCASH coin)!
☞ **-----CLICK HERE-----**⭐ ⭐ ⭐
Thanks for visiting and watching! Please don’t forget to leave a like, comment and share!

#javascript #learn javascript #learn javascript for beginners #learn javascript - full course for beginners #javascript programming language

Lowa Alice

Lowa Alice

1624379820

JavaScript Tutorial for Beginners: Learn JavaScript in 1 Hour

Watch this JavaScript tutorial for beginners to learn JavaScript basics in one hour.
avaScript is one of the most popular programming languages in 2019. A lot of people are learning JavaScript to become front-end and/or back-end developers.

I’ve designed this JavaScript tutorial for beginners to learn JavaScript from scratch. We’ll start off by answering the frequently asked questions by beginners about JavaScript and shortly after we’ll set up our development environment and start coding.

Whether you’re a beginner and want to learn to code, or you know any programming language and just want to learn JavaScript for web development, this tutorial helps you learn JavaScript fast.

You don’t need any prior experience with JavaScript or any other programming languages. Just watch this JavaScript tutorial to the end and you’ll be writing JavaScript code in no time.

If you want to become a front-end developer, you have to learn JavaScript. It is the programming language that every front-end developer must know.

You can also use JavaScript on the back-end using Node. Node is a run-time environment for executing JavaScript code outside of a browser. With Node and Express (a popular JavaScript framework), you can build back-end of web and mobile applications.

If you’re looking for a crash course that helps you get started with JavaScript quickly, this course is for you.

⭐️TABLE OF CONTENT ⭐️

00:00 What is JavaScript
04:41 Setting Up the Development Environment
07:52 JavaScript in Browsers
11:41 Separation of Concerns
13:47 JavaScript in Node
16:11 Variables
21:49 Constants
23:35 Primitive Types
26:47 Dynamic Typing
30:06 Objects
35:22 Arrays
39:41 Functions
44:22 Types of Functions

📺 The video in this post was made by Programming with Mosh
The origin of the article: https://www.youtube.com/watch?v=W6NZfCO5SIk&list=PLTjRvDozrdlxEIuOBZkMAK5uiqp8rHUax&index=2
🔥 If you’re a beginner. I believe the article below will be useful to you ☞ What You Should Know Before Investing in Cryptocurrency - For Beginner
⭐ ⭐ ⭐The project is of interest to the community. Join to Get free ‘GEEK coin’ (GEEKCASH coin)!
☞ **-----CLICK HERE-----**⭐ ⭐ ⭐
Thanks for visiting and watching! Please don’t forget to leave a like, comment and share!

#javascript #javascript tutorial #javascript tutorial for beginners #beginners

JavaScript Prototypes. It Doesn't Have to Be Complicated.

It’s hard to skip prototypes (or the prototype chain or prototypal inheritance) if you want to dive deeper into JS development (Not only pure JS, but also Node.js, Frameworks like Vue.js, React.js, Angular,…).

If you are like me a few years ago and get some serious headache each time you have to deal with prototypes in JavaScript, this will probably be THE article you were looking for to get your head wrapped around the principle of prototypes in JS.

From the  MDN documentation (don’t be scared, we’ll clarify everything below):

When it comes to inheritance, JavaScript only has one construct: objects. Each object has a private property (referred to as [[Prototype]]) which holds a link to another object called its prototype. That prototype object has a prototype of its own, and so on until an object is reached with null as its prototype. By definition, null has no prototype, and acts as the final link in this prototype chain.

Private [[Prototype]] property

Refer back to the below illustration whenever you feel the need, it might help you to wrap your head around this concept easier.

Prototype chain

So let’s start from the base. Every object in JavaScript has a private [[Prototype]] prototype, which holds a reference to another object (or null). This means, that our new object will have access to methods and properties of that referenced object.

#javascript #prototypes #prototypal inheritance #prototype chain

Madilyn  Kihn

Madilyn Kihn

1591242495

Prototypal Inheritance — The second pillar of Javascript

All you need to know about Prototypal Inheritance — The second pillar of Javascript
What we will learn here will help us understand Object-oriented programming(OOP).

#javascript #prototyping #prototype #prototype-chain #js

wp codevo

wp codevo

1608042336

JavaScript Shopping Cart - Javascript Project for Beginners

https://youtu.be/5B5Hn9VvrVs

#shopping cart javascript #hopping cart with javascript #javascript shopping cart tutorial for beginners #javascript cart project #javascript tutorial #shopping cart