Home Web Front-end JS Tutorial About JavaScript's object-oriented and inheritance, it is helpful for novices to learn_javascript skills

About JavaScript's object-oriented and inheritance, it is helpful for novices to learn_javascript skills

May 16, 2016 pm 05:43 PM
inherit object-oriented

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 is a regular function
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 of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed explanation of C++ function inheritance: How to use 'base class pointer' and 'derived class pointer' in inheritance? Detailed explanation of C++ function inheritance: How to use 'base class pointer' and 'derived class pointer' in inheritance? May 01, 2024 pm 10:27 PM

In function inheritance, use "base class pointer" and "derived class pointer" to understand the inheritance mechanism: when the base class pointer points to the derived class object, upward transformation is performed and only the base class members are accessed. When a derived class pointer points to a base class object, a downward cast is performed (unsafe) and must be used with caution.

Detailed explanation of C++ function inheritance: How to debug errors in inheritance? Detailed explanation of C++ function inheritance: How to debug errors in inheritance? May 02, 2024 am 09:54 AM

Inheritance error debugging tips: Ensure correct inheritance relationships. Use the debugger to step through the code and examine variable values. Make sure to use the virtual modifier correctly. Examine the inheritance diamond problem caused by hidden inheritance. Check for unimplemented pure virtual functions in abstract classes.

How do inheritance and polymorphism affect class coupling in C++? How do inheritance and polymorphism affect class coupling in C++? Jun 05, 2024 pm 02:33 PM

Inheritance and polymorphism affect the coupling of classes: Inheritance increases coupling because the derived class depends on the base class. Polymorphism reduces coupling because objects can respond to messages in a consistent manner through virtual functions and base class pointers. Best practices include using inheritance sparingly, defining public interfaces, avoiding adding data members to base classes, and decoupling classes through dependency injection. A practical example showing how to use polymorphism and dependency injection to reduce coupling in a bank account application.

Explore object-oriented programming in Go Explore object-oriented programming in Go Apr 04, 2024 am 10:39 AM

Go language supports object-oriented programming through type definition and method association. It does not support traditional inheritance, but is implemented through composition. Interfaces provide consistency between types and allow abstract methods to be defined. Practical cases show how to use OOP to manage customer information, including creating, obtaining, updating and deleting customer operations.

Detailed explanation of C++ function inheritance: How to understand the 'is-a' and 'has-a' relationship in inheritance? Detailed explanation of C++ function inheritance: How to understand the 'is-a' and 'has-a' relationship in inheritance? May 02, 2024 am 08:18 AM

Detailed explanation of C++ function inheritance: Master the relationship between "is-a" and "has-a" What is function inheritance? Function inheritance is a technique in C++ that associates methods defined in a derived class with methods defined in a base class. It allows derived classes to access and override methods of the base class, thereby extending the functionality of the base class. "is-a" and "has-a" relationships In function inheritance, the "is-a" relationship means that the derived class is a subtype of the base class, that is, the derived class "inherits" the characteristics and behavior of the base class. The "has-a" relationship means that the derived class contains a reference or pointer to the base class object, that is, the derived class "owns" the base class object. SyntaxThe following is the syntax for how to implement function inheritance: classDerivedClass:pu

Analysis of object-oriented features of Go language Analysis of object-oriented features of Go language Apr 04, 2024 am 11:18 AM

The Go language supports object-oriented programming, defining objects through structs, defining methods using pointer receivers, and implementing polymorphism through interfaces. The object-oriented features provide code reuse, maintainability and encapsulation in the Go language, but there are also limitations such as the lack of traditional concepts of classes and inheritance and method signature casts.

PHP Advanced Features: Best Practices in Object-Oriented Programming PHP Advanced Features: Best Practices in Object-Oriented Programming Jun 05, 2024 pm 09:39 PM

OOP best practices in PHP include naming conventions, interfaces and abstract classes, inheritance and polymorphism, and dependency injection. Practical cases include: using warehouse mode to manage data and using strategy mode to implement sorting.

Are there any class-like object-oriented features in Golang? Are there any class-like object-oriented features in Golang? Mar 19, 2024 pm 02:51 PM

There is no concept of a class in the traditional sense in Golang (Go language), but it provides a data type called a structure, through which object-oriented features similar to classes can be achieved. In this article, we'll explain how to use structures to implement object-oriented features and provide concrete code examples. Definition and use of structures First, let's take a look at the definition and use of structures. In Golang, structures can be defined through the type keyword and then used where needed. Structures can contain attributes

See all articles