search
HomeWeb Front-endJS TutorialAbout JavaScript's object-oriented and inheritance, it is helpful for novices to learn_javascript skills

This is an article about object-oriented and inheritance in JavaScript. It was written 1 year ago. The author takes it step by step. It is very helpful for students who want to learn object-oriented in JavaScript, so I try to translate it. Please correct me if I am wrong. Original link Objects and Inheritance in Javascript

While some Javascript users may never need to know about prototypes or the nature of object-oriented languages, developers who come from traditional object-oriented languages ​​will find inheritance in JavaScript when they use it. The model is very strange. Different JS frameworks provide their own methods to write class-like code, which makes JS object-oriented even more difficult to understand. The results of this are:
1. There is no standard way to implement object-oriented.
2. The underlying concept of object-oriented JS is not well known by people

Prototypal inheritance
Prototypal inheritance is a very simple concept, and its essence is:
1. Object a inherits from object b, which means b is the prototype of a.
2. a inherits all the attributes of b, that is, if the value of b. >Let's see the effect in concrete code, assuming there is a John Smith and a Jane that inherits from him.



Copy code The code is as follows: var john = {firstName: 'John', lastName: 'Smith'};
var jane = {firstName: 'Jane'};
jane.__proto__ = john;


Now, we call john the prototype of jane, jane inherits all the attributes of john


Copy code The code is as follows: jane.lastName
"Smith"//This attribute is inherited from john


jane's own attributes have higher priority, as follows


Copy code The code is as follows: jane.firstName;//This attribute overrides the firstName attribute in john
"Jane"


If you add an attribute to john after this, jane will also inherit the attribute dynamically, as shown below


Copy code The code is as follows: john.hair = 'brown'; //Add a new attribute to john
jane.hair;
"brown"//The result shows that jane inherits the new addition Properties of


Now, let’s assume that jane gets married and therefore has a new last name (last name)


Copy code The code is as follows: jane.lastName = 'Doe'

This attribute overrides the attribute with the same name (lastName) in john


Copy code The code is as follows: jane.lastName
"Doe"


However, if we now delete jane’s lastName


Copy the code The code is as follows: delete jane.lastName
The value of this attribute will be restored to john's value
[code]
jane.lastName
"Smith"


Now, jane can also Inherited from other objects. There can be any number of inheritances in this chain. We call it the prototype chain. In fact, john also has a prototype attribute


Copy code The code is as follows: john.__proto__;
Object { }


In the Firebug console, the value of john.__proto__ is set to Object{}, but Object{} represents the object Object.prototype - the parent class of all objects.

This is a brief description of prototypal inheritance. Looks pretty good, right?
However, in fact, we cannot use __proto__. . .

Let me tell you some bad news...
IE does not support the __proto__ attribute. In fact, __proto__ is not an attribute in the ECMAScript specification, and Mozilla also plans to add it to Firefox This attribute will be removed in future versions of the browser.

However, this does not mean that the __proto__ attribute does not exist. Although the __proto__ attribute cannot be directly accessed in some browsers, it still exists in some form, and we still have to deal with it, but it is not so direct.

Classes and Inheritance
Therefore, we can say that JavaScript does not have classes
Please remember: there are no classes in JavaScript
In this case, what happens with methods and inheritance? What was achieved?
By prototype. In traditional object-oriented languages, methods depend on classes, but in JavaScript, methods depend on the prototype of the object, and the prototype is bound to the constructor of the object.

In JavaScript, functions play the role of constructors. By using the new operator, you can use a function as a constructor. The code below shows us creating a Cat function:
Copy the code The code is as follows:

function Cat(name){ // this.name = name // this points to the new object
}

The above code will be automatically created A Cat.prototype object
Copy code The code is as follows:

Cat.prototype
Cat { }

We can use the new operator to create an instance of Cat
Copy code The code is as follows :

var garfield = new Cat('Garfield') // Create an instance - the Cat function acts as the constructor

Now, the Cat.prototype object becomes all The prototype of the object created by new Cat(), for example:
Copy code The code is as follows:

garfield.__proto__ === Cat.prototype
true //See? `Cat.prototype` is now the prototype of the garfield object

Now, we add a Cat.prototype Method, after adding, the method can be accessed by garfield
Copy code The code is as follows:

Cat.prototype.greet = function(){
console.log('Meow, I am ' this.name)
}
garfield.greet()
"Meow, I am Garfield"

Other Cat instances can also access
Copy the code The code is as follows:

var felix = new Cat('Felix')
felix.greet()
"Meow, I am Felix"

So, in JavaScript, the method is Depends on the object's prototype (prototype).

In fact, we can also add a method to garfield, which will override the method of the same name in Cat.prototype, as shown below:
Copy code The code is as follows:

garfield.greet = function(){
console.log("What's new?");
};
garfield.greet();
"What's new?"

But this will not affect other objects
Copy Code The code is as follows:

felix.greet();
"Meow, I am Felix"

Therefore, in JavaScript, a method can be directly associated with an object, with the prototype of the object, or with any parent object of the object, that is, with any link in the prototype chain. This is how inheritance is implemented.

To create a secondary prototype chain, we first need to create another constructor, how about calling it Animal?
Copy code The code is as follows:

function Animal(){
}

Next, we need to point the prototype of Cat.prototype to an Animal object, so that the Cat instance will inherit all Animal methods. Therefore, we set the value of Cat.prototype to an instance of Animal as follows:
Copy code The code is as follows:

Cat.prototype = new Animal();

In addition, we also need to tell the new Cat.prototype that it is actually an instance of Cat:
Copy code The code is as follows:

Cat.prototype.constructor = Cat // Let `Cat. prototype` knows that it is an instance of Cat

Although the purpose of doing this is mainly for the hierarchical relationship between classes, it is usually necessary to do this.

Now, since the objects inherited from Animal.prototype and Cat.prototype belong to the animal class, all instances of Cat also indirectly inherit from Animal.prototype. If we add a new method to Animal.prototype, then all instances of Cat can also access this method.
Copy code The code is as follows:

Animal.prototype.breed = function(){
console.log('Making a new animal!');
return new this.constructor();
};
var kitty = garfield.breed();
Making a new animal!

Through the above code we have achieved inheritance, it’s simple.

Conclusion
Although prototype-based inheritance in JavaScript is weird and takes some time to get used to, its core idea is very simple. As long as you truly understand these essential concepts, you will have the confidence to control JavaScript OO in these mixed codes. (End)^_^
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
如何使用Go语言实现面向对象的事件驱动编程如何使用Go语言实现面向对象的事件驱动编程Jul 20, 2023 pm 10:36 PM

如何使用Go语言实现面向对象的事件驱动编程引言:面向对象的编程范式被广泛应用于软件开发中,而事件驱动编程是一种常见的编程模式,它通过事件的触发和处理来实现程序的流程控制。本文将介绍如何使用Go语言实现面向对象的事件驱动编程,并提供代码示例。一、事件驱动编程的概念事件驱动编程是一种基于事件和消息的编程模式,它将程序的流程控制转移到事件的触发和处理上。在事件驱动

解析PHP面向对象编程中的享元模式解析PHP面向对象编程中的享元模式Aug 14, 2023 pm 05:25 PM

解析PHP面向对象编程中的享元模式在面向对象编程中,设计模式是一种常用的软件设计方法,它可以提高代码的可读性、可维护性和可扩展性。享元模式(Flyweightpattern)是设计模式中的一种,它通过共享对象来降低内存的开销。本文将探讨如何在PHP中使用享元模式来提高程序性能。什么是享元模式?享元模式是一种结构型设计模式,它的目的是在不同对象之间共享相同的

go语言是面向对象的吗go语言是面向对象的吗Mar 15, 2021 am 11:51 AM

go语言既不是面向对象,也不是面向过程,因为Golang并没有明显的倾向,而是更倾向于让编程者去考虑该怎么去用它,也许它的特色就是灵活,编程者可以用它实现面向对象,但它本身不支持面向对象的语义。

python是面向对象还是面向过程python是面向对象还是面向过程Jan 05, 2023 pm 04:54 PM

python是面向对象的。Python语言在设计之初,就定位为一门面向对象的编程语言,“Python中一切皆对象”就是对Pytho 这门编程语言的完美诠释。类和对象是Python的重要特征,相比其它面向对象语言,Python很容易就可以创建出一个类和对象;同时,Python也支持面向对象的三大特征:封装、继承和多态。

PHP面向对象编程入门指南PHP面向对象编程入门指南Jun 11, 2023 am 09:45 AM

PHP作为一种广泛使用的编程语言,已成为构建动态网站和网络应用程序的首选语言之一。其中,面向对象编程(OOP)的概念和技术越来越受到开发者的欢迎和推崇。本篇文章将为读者提供PHP面向对象编程的入门指南,介绍OOP的基本概念,语法和应用。什么是面向对象编程(OOP)?面向对象编程(Object-OrientedProgramming,简称OOP),是一种编程

如何使用Go语言实现面向对象的数据库访问如何使用Go语言实现面向对象的数据库访问Jul 25, 2023 pm 01:22 PM

如何使用Go语言实现面向对象的数据库访问引言:随着互联网的发展,大量的数据需要被存储和访问,数据库成为了现代应用开发中的重要组成部分。而作为一门现代化、高效性能的编程语言,Go语言很适合用来处理数据库操作。而本文将重点讨论如何使用Go语言实现面向对象的数据库访问。一、数据库访问的基本概念在开始讨论如何使用Go语言实现面向对象的数据库访问之前,我们先来了解一下

Python中的面向对象编程Python中的面向对象编程Jun 10, 2023 pm 05:19 PM

Python作为一种高级编程语言,在众多编程语言中占有举足轻重的地位。它的语法简单易学,拥有各种强大的编程库,被广泛应用于数据处理、机器学习、网络编程等领域。而其中最重要的一点便是Python完美支持面向对象编程,本文将重点阐述Python中的面向对象编程。一、面向对象编程的基本概念在面向对象的编程语言中,数据和方法被封装在对象的内部。这使得对象能够独立地进

java什么是面向对象java什么是面向对象May 20, 2019 pm 01:53 PM

java面向对象是指在计算机程序中,模拟现实世界中的概念,借助对象的描述在计算机程序中用类似的实体模拟现实世界中的实体。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool