Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Analysis of prototypes and inheritance examples in JavaScript

2025-02-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "prototype and inheritance example Analysis in JavaScript". In daily operation, I believe that many people have doubts about prototype and inheritance example analysis in JavaScript. The editor consulted all kinds of data and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "prototype and inheritance example Analysis in JavaScript". Next, please follow the editor to study!

Introduction

JavaScript is a prototype-based language, which means that object properties and methods can be shared through generic objects with cloning and extensibility. This is called prototype inheritance, unlike class inheritance. In popular object-oriented programming languages, JavaScript is relatively unique because other well-known languages, such as PHP, Python, and Java, are class-based languages that define classes as blueprints for objects.

In this article, we will learn what an object prototype is and how to use constructors to extend the prototype to a new object. We will also learn about inheritance and prototype chains.

JavaScript prototype

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

Let x = {}

This is how we usually create objects, but note that another way to do this is to use the object constructor:

Let x = new object ()

The parentheses surrounding [[Prototype]] indicate that it is an internal attribute and cannot be accessed directly in the 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.

Output:

{constructor: please, _ _ defineGetter__:, _ _ defineSetter__:, … }

Another way to find [[Prototype]] is through _ _ proto__ property. _ _ proto__ is a property that exposes the interior of the [[Prototype]] object.

It should be noted that. _ proto__ is a legacy feature that should not be used in production code, and it does not exist in every modern browser. However, we can use it for demonstration in this article.

X.__proto__

The output will be the same as using getPrototypeOf ().

Output

{constructor: please, _ _ defineGetter__:, _ _ defineSetter__:, … }

It is important that every object in JavaScript has a [[Prototype]] because it creates a linked method for any two or more objects.

The objects you create have the same [[Prototype]] as built-in objects such as Date and Array. You can reference this internal property from one object to another through the prototype property, as we'll see later in this tutorial.

Prototype inheritance

When you try to access an object's properties or methods, JavaScript first searches for the object itself, and if it does not find it, it searches for the object's [[Prototype]]. If no match is found after querying the object and its [[Prototype]], JavaScript checks the prototype of the linked object and continues the search until it reaches the end of the prototype chain.

The end of the prototype chain is Object.prototype. All objects inherit the properties and methods of the object. Any search beyond the end of the chain will result in null.

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

X.toString ()

Output

[object Object]

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

X.__proto__.__proto__

Output

Null

Let's look at another type of object. If you have experience working with arrays with JavaScript, you know that they have many built-in methods, such as pop () and push (). The reason you can access these methods when you create a new array is that any array you create can access the properties and methods on array. Prototype.

We can test it by creating a new array.

Let y = []

Remember, we can also write it as an array constructor with y = new array ().

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

[constructor: eggs, concat: eggs, pop: eggs, push: eggs, etc.]

You will notice that the constructor property on the prototype is set to Array (). The constructor property returns the constructor of the object, which is a mechanism for constructing the object from the function.

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

{constructor: eggs, _ _ defineGetter__: eggs, _ _ defineSetter__: eggs,... }

This chain now refers to Object.prototype. We can test the internal [[Prototype]] against the Prototype property of the constructor to make sure that they refer to the same thing.

.protoplast _ = Array.prototype; / / truey.__proto__.__proto__ = Object.prototype; / / true

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

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

We can use the instanceof operator to test whether the prototype property of the constructor appears anywhere in the object prototype chain.

Y instanceof Array; / / true

In summary, all JavaScript objects have hidden internal [[Prototype]] properties (perhaps _ _ proto__ is exposed in some browsers). Object can be extended and will inherit the properties and methods of its constructor [[Prototype]].

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

Constructor function

A constructor is a function used to construct a new object. The new operator is used to create new instances based on the constructor. We have seen some built-in JavaScript constructors, such as new Array () and new Date (), but we can also create our own custom templates to build new objects.

For example, we are creating a very simple text-based role-playing game. Users can select a role, and then select the categories of roles they will have, such as warriors, healers, thieves, and so on.

Because each character will share many features, such as a name, level, and life value, it makes sense to create a constructor as a template. However, because each role class may have very different capabilities, we want to ensure that each role can only access its own capabilities. Let's look at how to do this using prototype inheritance and constructors.

First, the constructor is just a normal function. When it is called by an instance using the new keyword, it becomes a constructor. In JavaScript, we capitalize the first letter of the constructor by convention.

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

We created a constructor called Hero, which takes two parameters: name and level. Because each character has a name and a level, it makes sense for every new character to have these attributes. The this keyword references the new instance created, so setting this.name to the name parameter ensures that the new object has the name property set.

Now we can create a new instance with new.

Let hero1 = new Hero ('Bjorn', 1)

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

Output

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

Now, if we get the [[Prototype]] of hero1, we will be able to see the constructor Hero (). Remember, it has the same input as hero1. But this is the right way.)

Object.getPrototypeOf (hero1)

Output

Constructor: Hero (name, level)

You may notice that we only define properties in the constructor, not methods. In JavaScript, methods are usually defined on prototypes to improve efficiency and code readability.

We can use prototype to add a method to Hero. We will create a greet () method.

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

Because greet () is in the prototype of Hero, and hero1 is an instance of Hero, this method is available for hero1.

Hero1.greet ()

Output

"Bjorn says hello."

If you check Hero's [[Prototype]], you will see that greet () is now an available option.

That's good, but now we want to create character classes for heroes. It doesn't make sense to put all the functionality of each class in the Hero constructor, because different classes have different functions. We want to create new constructors, but we also want them to connect to the original Hero.

We can use the call () method to copy properties from one constructor to another. Let's create a warrior and a healing constructor.

/ Initialize Warrior constructorfunction Warrior (name, level, weapon) {/ / Chain constructor with call Hero.call (this, name, level); / / Add a new property this.weapon = weapon;} / / Initialize Healer constructorfunction Healer (name, level, spell) {Hero.call (this, name, level); this.spell = spell;}

Both new constructors now have properties of Hero and unqiue. We will add the attack () method to the Warrior and the heal () method to the Healer.

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 will create characters using two new character classes that are available.

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

Hero1 is now considered a warrior with new attributes.

Output

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

We can use the new method we set up on the warrior prototype.

Hero1.attack (); Console "Bjorn attacks with the axe."

But what happens if we try to use the method below the prototype chain?

Hero1.greet ()

Output

Uncaught TypeError: hero1.greet is not a function

Prototype properties and methods are not automatically linked when you use the call () link constructor. We will use Object.create () to link the prototype, ensuring that it is placed before any other methods are created and added to the prototype.

Warrior.prototype = Object.create (Hero.prototype); Healer.prototype = Object.create (Hero.prototype); / / All other prototype methods added below...

Now we can successfully use Hero's prototype method on an example of a warrior or healer.

Hero1.greet ()

Output

"Bjorn says hello."

Here is the complete code for our character creation page.

/ Initialize constructor functionsfunction 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 methodsWarrior.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 instancesconst hero1 = new Warrior ('Bjorn', 1,' axe'); const hero2 = new Healer ('Kanin', 1,' cure')

Using this code, we have created the Hero class with basic properties, created two character classes named Warrior and Healer from the original constructor, added methods to the prototype, and created separate character instances.

At this point, the study of "sample analysis of prototypes and inheritance in JavaScript" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report