Home Web Front-end JS Tutorial Summary of usage of inheritance in javascript_javascript skills

Summary of usage of inheritance in javascript_javascript skills

May 16, 2016 pm 04:25 PM
javascript usage inherit

The examples in this article summarize the usage of inheritance in JavaScript. Share it with everyone for your reference. The details are as follows:

Example:

Copy code The code is as follows:
/**
* Implement the subclass to inherit the parent class, but will not generate redundant attributes and methods
* @returns {Function}
*/
define(function(){
return function(subType, superType){
var proto = new Object(superType.prototype);
proto.constructor = subType;
subType.prototype = proto;
};
});
//————————————————————————
define(function(){
function ostring(s)
{
this.str = s;
this.length = this.str.length;
}
ostring.prototype.show = function(){
alert(this.str);
};
return ostring;
});
//————————————————————————
define(['inherit', 'ostring'], function(inherit, ostring){
function wstring(s){
//Use call to call the parent class constructor
ostring.call(this, s);
this.chlength = 2 * s.length;
}
//Inherit other attributes
inherit(wstring, ostring);
wstring.prototype.add = function(w)
{
alert(this.str w);
};
return wstring;
});

Look at the example again
1. Use function to implement:

Copy code The code is as follows:
function Person(name) {
This.name = name;
}
Person.prototype.getName = function() {
Return this.name;
}
function Author(name, books) {
This.inherit=person;
This.inherit(name);
This.books = books;
 
}
var au=new Author("dororo","Learn much");
au.name

Or equivalent:
Copy code The code is as follows:
function Person(name) {
This.name = name;
}
Person.prototype.getName = function() {
Return this.name;
}
function Author(name, books) {
Person.call(this, name);
This.books = books;
 
}
var au=new Author("dororo","Learn much");
au.getName

Since this is just using this as a parameter, calling the constructor of the parent class Person, and assigning all the fields assigned to the parent class to the Author subclass, any defined fields (prototype) other than the parent class Person constructor will not be used by the subclass. will be inherited. So in the above example, au.getName will be undefined because getName is defined in the Person prototype object.

Moreover, the constructor of the subclass must call the constructor of the parent class before defining its own domain, so as to prevent the definition of the subclass from being overwritten by the parent class. In other words, the Author defined attribute book must be after Person.call, otherwise it will be overwritten by the attributes in Person. At the same time, it is best not to use prototype to define the function domain of the subclass in the subclass, because after a subclass is new and instantiated, the prototype must be executed, and then the constructor of the parent class is called, which is also easy to be The attributes of the parent class are overwritten.

2. Use prototype to implement:

Copy code The code is as follows:
function Person(name) {
This.name = name;
}
Person.prototype.getName = function() {
Return this.name;
}
function Author(name, books) {
This.books = books;
}
Author.prototype=new Person(name);
Author.prototype.constructor=Author;
Author.prototype.getBooks = function() {
Return this.books;
}
var au1=new Author("dororo1","Learn much");
var au2=new Author("dororo2","Learn less");
alert(au1.getName());
alert(au2.getName());

This method avoids the problem of being unable to inherit prototype in function implementation. Because Author.prototype=new Person(name); new Person() instance will call the Person constructor and all properties of the prototype. But the disadvantage is that Author.prototype has already been instantiated. So when a subclass is instantiated, all non-basic data types are reference copies. So in the above example, the value returned by both instances au1 and au2 is dororo1.

3. Use “mixing” to achieve

Copy code The code is as follows:
function Person(name) {
This.name = name;
}
Person.prototype.getName = function() {
Return this.name;
}
function Author(name, books) {
This.base = new Person(name);
for(var key in this.base){
          if(!this[key]){
This[key]=this.base[key];
           }
           }
This.book=books;
}
var au1=new Author("dororo1","work");
var au2=new Author("dororo2","play");
alert(au1.getName());
alert(au2.getName());
au1.book;
au2.book;


It is an extension and copies all fields of the parent class to the child class. There are no problems with the above two aspects at all.
Parasitic combination mode)

JS inheritance includes attribute inheritance and method inheritance, which are implemented through different methods.
1. Inheritance of attributes

Inheritance of attributes is achieved by changing the execution environment of the function. Changing the execution environment of a function can be achieved using the call() and apply() methods.

We first create an Animal "class" (because there is no concept of class in JS, here is just a simulation, it is actually just a Function object).

Copy code The code is as follows:
function Animal(typeName) {
//Add an attribute typeName
to the execution environment (this) of the current method //But the execution environment (this) can only be determined when this function is executed
this.typeName = typeName;
this.colors = ["red","while"];
}
//Want to add two (object-shared) methods to the prototype of the function
Animal.prototype.Shout = function () { alert("I am: --" this.typeName);};
Animal.prototype.Eat = function () { alert("I am: --" this.typeName) };
//--Define a lion--"class" (actually a function)
function Lion(tn) {
//--Execute the Animal method, and modify the execution environment of Animal to Lion's this
through the first parameter of apply //Similarly, Lion’s this can only be determined during execution
Animal.apply(this,["Lion"]);//--Inherited the variable attributes of the parent class, this is new because it is Lion, this is Lion
}
Lion.prototype = Animal.prototype; //Inherit the method of the parent class and get it done--but this is not well written. When the subclass adds a method, the parent class also has this method. This is a pointer reference
Lion.prototype.Hunt = function () {
alert("I am: Lion, I want to hunt~~·~");
}
var aminm = new Animal();
aminm.Hunt(); //---You can access the methods of the subclass, which is not good
//----So how to solve this problem? ? ? ? ? ?
//---Solution: When inheriting methods, you can write like this:
Lion.prototype = new Animal();//Inherit the method of the parent class and assign the Animal object to the prototype prototype. In fact, it also has attributes
var lion = new Lion(); //In addition to creating, the new keyword also modifies the execution environment of the Lion object to the Lion object itself
// ---In other words, after new is completed, this in the Lion function is the Lion function itself, and then the Lion function
is called

Analyze the new keyword:

The new keyword is very great. In the above code, the new keyword has completed the following tasks:
1) Open up heap space to prepare to store Lion objects
2) Modify the execution environment of the Lion object itself so that this of the Lion function points to the Lion function object itself.
3) Call the "constructor" of the Lion "class" to create a Lion object
4) Assign the heap address of the Lion function object to the variable l. At this time, l points to the Lion function object
lion.Shout();
lion.Eat();
But this kind of inheritance has a disadvantage: the constructor of the parent class is called twice, call once, and then new again.

I hope this article will be helpful to everyone’s JavaScript programming design.

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

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 ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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.

Usage of WPSdatedif function Usage of WPSdatedif function Feb 20, 2024 pm 10:27 PM

WPS is a commonly used office software suite, and the WPS table function is widely used for data processing and calculations. In the WPS table, there is a very useful function, the DATEDIF function, which is used to calculate the time difference between two dates. The DATEDIF function is the abbreviation of the English word DateDifference. Its syntax is as follows: DATEDIF(start_date,end_date,unit) where start_date represents the starting date.

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.

Detailed explanation and usage introduction of MySQL ISNULL function Detailed explanation and usage introduction of MySQL ISNULL function Mar 01, 2024 pm 05:24 PM

The ISNULL() function in MySQL is a function used to determine whether a specified expression or column is NULL. It returns a Boolean value, 1 if the expression is NULL, 0 otherwise. The ISNULL() function can be used in the SELECT statement or for conditional judgment in the WHERE clause. 1. The basic syntax of the ISNULL() function: ISNULL(expression) where expression is the expression to determine whether it is NULL or

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.

C++ function inheritance explained: When should inheritance not be used? C++ function inheritance explained: When should inheritance not be used? May 04, 2024 pm 12:18 PM

C++ function inheritance should not be used in the following situations: When a derived class requires a different implementation, a new function with a different implementation should be created. When a derived class does not require a function, it should be declared as an empty class or use private, unimplemented base class member functions to disable function inheritance. When functions do not require inheritance, other mechanisms (such as templates) should be used to achieve code reuse.

Use CSS Transform to transform elements Use CSS Transform to transform elements Feb 24, 2024 am 10:09 AM

Usage of Transform in CSS The Transform property of CSS is a very powerful tool that can perform operations such as translation, rotation, scaling and tilting of HTML elements. It can dramatically change the appearance of elements and make web pages more creative and dynamic. In this article, we will introduce the various uses of Transform in detail and provide specific code examples. 1. Translate (Translate) Translate refers to moving an element a specified distance along the x-axis and y-axis. Its syntax is as follows: tran

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

See all articles