search
HomeWeb Front-endJS TutorialJavascript object-oriented programming (2) Inheritance of constructor_js object-oriented

What I want to introduce today is how to generate an instance that "inherits" multiple objects.
For example, there is now a constructor for the "animal" object,

Copy the code The code is as follows:

 function Animal(){
 this.species = "Animal";
 }

There is also a constructor for the "cat" object,
Copy code The code is as follows:

Function Cat(name,color){
this.name = name;
 this.color = color;
 }

How to make "cat" inherit "animal"?
1. Constructor binding
The simplest method is probably to use the call or apply method to bind the constructor of the parent object to the child object, that is, in the child object constructor Add a line to the function:
Copy code The code is as follows:

Function Cat(name,color) {
 Animal.apply(this, arguments);
this.name = name;
this.color = color;
}
var cat1 = new Cat("大毛","黄");
 alert(cat1.species); // Animals

2. prototype mode
The more common approach is to use the prototype attribute.
If the prototype object of "cat" points to an instance of Animal, then all instances of "cat" can inherit Animal.
Copy code The code is as follows:

Cat.prototype = new Animal();
Cat.prototype.constructor = Cat;
var cat1 = new Cat("Big Hair", "Yellow");
alert(cat1.species); // Animal

code In the first line, we point Cat's prototype object to an Animal instance.
 Cat.prototype = new Animal();
It is equivalent to completely deleting the original value of the prototype object and then assigning a new value. But what does the second line mean?
Cat.prototype.constructor = Cat;
It turns out that any prototype object has a constructor attribute pointing to its constructor. In other words, the constructor property of the Cat.prototype object points to Cat.
We have deleted the original value of this prototype object in the previous step, so the new prototype object does not have a constructor attribute, so we must add it manually, otherwise there will be problems with the "inheritance chain" later. This is what the second line means.
In short, this is a very important point and must be followed when programming. The following follows this point, that is, if the prototype object is replaced,
 o.prototype = {};
Then the next step must be to add the constructor attribute to the new prototype object and point this attribute back to the original Constructor.
 o.prototype.constructor = o;
3. Directly inherit prototype
Since in the Animal object, the unchanged attributes can be written directly to Animal.prototype. Therefore, we can also let Cat() skip Animal() and inherit Animal.prototype directly.
Now, let’s rewrite the Animal object first:
Copy the code The code is as follows:

function Animal(){ }
 Animal.prototype.species = "Animal";

Then, point the prototype object of Cat to the prototype object of Animal, thus completing the inheritance.
Copy code The code is as follows:

Cat.prototype = Animal.prototype;
Cat .prototype.constructor = Cat;
var cat1 = new Cat("Big Hair","Yellow");
alert(cat1.species); // Animal

Compared with the previous method, the advantage of this method is that it is more efficient (no need to execute and create an instance of Animal) and saves memory. The disadvantage is that Cat.prototype and Animal.prototype now point to the same object, so any modifications to Cat.prototype will be reflected in Animal.prototype.
So, the above code is actually problematic. Please look at the second line
Cat.prototype.constructor = Cat;
This sentence actually changes the constructor property of the Animal.prototype object!
 alert(Animal.prototype.constructor); // Cat
4. Use empty objects as intermediaries
Since "directly inherit prototype" has the above shortcomings, you can use an empty object Objects act as intermediaries.
Copy code The code is as follows:

 var F = function(){};
F.prototype = Animal.prototype;
Cat.prototype = new F();
Cat.prototype.constructor = Cat;

F is an empty object, so it takes up almost no memory . At this time, modifying the prototype object of Cat will not affect the prototype object of Animal.
 alert(Animal.prototype.constructor); // Animal
5. Encapsulation function of prototype mode
We encapsulate the above method into a function for ease of use.
Copy code The code is as follows:

Function extend(Child, Parent) {
var F = function(){};
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
Child.uber = Parent .prototype;
 }

When used, the method is as follows
Copy the code The code is as follows :

extend(Cat,Animal);
var cat1 = new Cat("Big Hair","Yellow");
alert(cat1.species); // Animal

This extend function is how the YUI library implements inheritance.
Also, let me explain something. The last line of the function body
Child.uber = Parent.prototype;
means to set an uber attribute for the child object, which directly points to the prototype attribute of the parent object. This is equivalent to opening a channel on the child object, and you can directly call the method of the parent object. This line is placed here just to achieve the completeness of inheritance and is purely for backup purposes.
6. Copy inheritance
The above uses prototype objects to implement inheritance. We can also change our thinking and purely use the "copy" method to implement inheritance. To put it simply, if you copy all the properties and methods of the parent object into the child object, wouldn't inheritance also be achieved?
First of all, put all the immutable properties of Animal on its prototype object.
Copy code The code is as follows:

function Animal(){}
Animal.prototype .species = "Animal";

Then, write a function to achieve the purpose of attribute copying.
Copy code The code is as follows:

Function extend2(Child, Parent) {
  var p = Parent.prototype;
var c = Child.prototype;
for (var i in p) {
c[i] = p[i];
c.uber = p;
 }

The function of this function is to copy the attributes in the prototype object of the parent object to the prototype object of the Child object one by one. When using
, write like this:

Copy code The code is as follows:
extend2( Cat, Animal);
var cat1 = new Cat("Big Hair", "Yellow");
alert(cat1.species); // Animal

Not finished yet, please continue reading Part 3 "Non-Constructor Inheritance".
(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
解决PHP报错:继承父类时遇到的问题解决PHP报错:继承父类时遇到的问题Aug 17, 2023 pm 01:33 PM

解决PHP报错:继承父类时遇到的问题在PHP中,继承是一种重要的面向对象编程的特性。通过继承,我们能够重用已有的代码,并且能够在不修改原有代码的情况下,对其进行扩展和改进。尽管继承在开发中应用广泛,但有时候在继承父类时可能会遇到一些报错问题,本文将围绕解决继承父类时遇到的常见问题进行讨论,并提供相应的代码示例。问题一:未找到父类在继承父类的过程中,如果系统无

使用继承的Java程序来计算定期存款(FDs)和定期存款(RDs)的利息使用继承的Java程序来计算定期存款(FDs)和定期存款(RDs)的利息Aug 20, 2023 pm 10:49 PM

继承是一个概念,它允许我们从一个类访问另一个类的属性和行为。被继承方法和成员变量的类被称为超类或父类,而继承这些方法和成员变量的类被称为子类或子类。在Java中,我们使用“extends”关键字来继承一个类。在本文中,我们将讨论使用继承来计算定期存款和定期存款的利息的Java程序。首先,在您的本地机器IDE中创建这四个Java文件-Acnt.java−这个文件将包含一个抽象类‘Acnt’,用于存储账户详情,如利率和金额。它还将具有一个带有参数‘amnt’的抽象方法‘calcIntrst’,用于计

如何在PHP中使用多态和继承来处理数据类型如何在PHP中使用多态和继承来处理数据类型Jul 15, 2023 pm 07:41 PM

如何在PHP中使用多态和继承来处理数据类型引言:在PHP中,多态和继承是两个重要的面向对象编程(OOP)概念。通过使用多态和继承,我们可以更加灵活地处理不同的数据类型。本文将介绍如何在PHP中使用多态和继承来处理数据类型,并通过代码示例展示它们的实际应用。一、继承的基本概念继承是面向对象编程中的一种重要概念,它允许我们创建一个类,该类可以继承父类的属性和方法

PHP中的封装技术及应用PHP中的封装技术及应用Oct 12, 2023 pm 01:43 PM

PHP中的封装技术及应用封装是面向对象编程中的一个重要概念,它指的是将数据和对数据的操作封装在一起,以便提供对外部程序的统一访问接口。在PHP中,封装可以通过访问控制修饰符和类的定义来实现。本文将介绍PHP中的封装技术及其应用场景,并提供一些具体的代码示例。一、封装的访问控制修饰符在PHP中,封装主要通过访问控制修饰符来实现。PHP提供了三个访问控制修饰符,

PHP中的多重继承PHP中的多重继承Aug 23, 2023 pm 05:53 PM

继承:继承是面向对象编程(OOP)中的一个基本概念,它允许类从其他类继承属性和行为。它是一种基于现有类创建新类的机制,促进代码重用并建立类之间的层次关系。继承基于"父子"或"超类-子类"关系的概念。从中继承的类被称为超类或基类,而继承超类的类被称为子类或派生类。子类继承其超类的所有属性(变量)和方法(函数),还可以添加自己独特的属性和方法或覆盖继承的属性和方法继承的类型在面向对象编程(OOP)中,继承是一个基本概念,它允许类从其他类中继承属性和行为。它促进

如何使用Java强制继承代理final类?如何使用Java强制继承代理final类?Sep 06, 2023 pm 01:27 PM

如何使用Java强制继承代理final类?在Java中,final关键字用于修饰类、方法和变量,表示它们不可被继承、重写和修改。然而,在某些情况下,我们可能需要强制继承一个final类,以实现特定的需求。本文将讨论如何使用代理模式来实现这样的功能。代理模式是一种结构型设计模式,它允许我们创建一个中间对象(代理对象),该对象可以控制对另一个对象(被代理对象)的

Python中的构造函数Python中的构造函数Sep 02, 2023 pm 04:29 PM

在Python中,每个类都有一个构造函数,它是类内部指定的特殊方法。构造函数/初始化程序将在为类创建新对象时自动调用。当对象被初始化时,构造函数将值分配给类中的数据成员。没有必要显式定义构造函数。但为了创建构造函数,我们需要遵循以下规则-对于一个类,它只允许有一个构造函数。构造函数名称必须是__init__。必须使用实例属性定义构造函数(只需将self关键字指定为第一个参数)。它不能返回除None之外的任何值。语法classA():def__init__(self):pass示例考虑下面的示例并

继承、多态与接口:PHP面向对象的三大特性继承、多态与接口:PHP面向对象的三大特性May 11, 2023 pm 03:45 PM

PHP是一种服务器端编程语言,自PHP5之后开始支持面向对象编程(OOP)。OOP的核心思想是将数据和行为封装在对象中,以提高程序的可维护性和可扩展性。在PHP中,面向对象编程具有三大特性:继承、多态与接口。一、继承继承是指一个类可以从另一个类中继承属性和方法。被继承的类称为父类或基类,继承的类称为子类或派生类。子类可以通过继承获得父类中的属性和方法,并且可

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

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software