


Javascript 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,
function Animal(){
this.species = "Animal";
}
There is also a constructor for the "cat" object,
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:
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.
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:
function Animal(){ }
Animal.prototype.species = "Animal";
Then, point the prototype object of Cat to the prototype object of Animal, thus completing the inheritance.
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.
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.
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
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.
function Animal(){}
Animal.prototype .species = "Animal";
Then, write a function to achieve the purpose of attribute copying.
Function extend2(Child, Parent) {
var p = Parent.prototype;
var c = Child.prototype;
for (var i in p) {
c[i] = p[i];
c.uber = p;
}
, write like this:
var cat1 = new Cat("Big Hair", "Yellow");
alert(cat1.species); // Animal
(End)

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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.

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.

Solving PHP errors: Problems encountered when inheriting parent classes In PHP, inheritance is an important feature of object-oriented programming. Through inheritance, we can reuse existing code and extend and improve it without modifying the original code. Although inheritance is widely used in development, sometimes you may encounter some error problems when inheriting from a parent class. This article will focus on solving common problems encountered when inheriting from a parent class and provide corresponding code examples. Question 1: The parent class is not found. During the process of inheriting the parent class, if the system does not

Inheritance is a concept that allows us to access the properties and behavior of one class from another class. The class that inherits methods and member variables is called a superclass or parent class, and the class that inherits these methods and member variables is called a subclass or subclass. In Java, we use "extends" keyword to inherit a class. In this article, we will discuss a Java program to calculate interest on fixed deposits and time deposits using inheritance. First, create these four Java files - Acnt.java − in your local machine IDE. This file will contain an abstract class ‘Acnt’ which is used to store account details like interest rate and amount. It will also have an abstract method 'calcIntrst' with parameter 'amnt' for calculating

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.

Encapsulation technology and application encapsulation in PHP is an important concept in object-oriented programming. It refers to encapsulating data and operations on data together in order to provide a unified access interface to external programs. In PHP, encapsulation can be achieved through access control modifiers and class definitions. This article will introduce encapsulation technology in PHP and its application scenarios, and provide some specific code examples. 1. Encapsulated access control modifiers In PHP, encapsulation is mainly achieved through access control modifiers. PHP provides three access control modifiers,

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

Inheritance: Inheritance is a fundamental concept in object-oriented programming (OOP) that allows classes to inherit properties and behavior from other classes. It is a mechanism for creating new classes based on existing classes, promoting code reuse and establishing hierarchical relationships between classes. Inheritance is based on the concept of "parent-child" or "superclass-child" relationship. The class that inherits from it is called a super class or base class, while the class that inherits from a super class is called a subclass or derived class. Subclasses inherit all properties (variables) and methods (functions) of their superclass, and can also add their own unique properties and methods or override inherited properties and methods. Inherited types In object-oriented programming (OOP), inheritance is a basic Concept that allows classes to inherit properties and behavior from other classes. it promotes
