Home Web Front-end JS Tutorial A brief discussion on javascript prototype chain and inheritance_javascript skills

A brief discussion on javascript prototype chain and inheritance_javascript skills

May 16, 2016 pm 03:50 PM
javascript prototype chain inherit

JS prototype chain and inheritance are the key points in JS, so we will explain them in detail through the following three examples.

First define an object obj. The prototype of the object is obj._proto_. We can use the getPrototypeOf method in ES5 to query the prototype of obj. We prove whether it exists by judging whether the prototype of obj is equal to Object.prototype. The prototype of obj, the answer returns true, so it exists. Then we define a function foo(). Any function has its prototype object, that is, the prototype of the function. We can add any attributes to the prototype of the function, and then an instantiated object can share its attributes through new (below) Two examples will be introduced in detail).

function foo(){}
foo.prototype.z = 3;
var obj = new foo();
obj.x=1;
obj.y=2;
obj.x //1
obj.y //2
obj.z //3
typeof obj.toString; //function
obj.valueOf(); // foo {x: 1, y: 2, z: 3}
obj.hasOwnProperty('z'); //false

Copy after login

Here, the prototype of obj (_proto_) points to the prototype attribute of the foo function, the prototype of foo.prototype points to Object.prototype, and the end of the prototype chain is null. Use hasOwnProperty to check whether the z attribute is on obj. It is displayed. false, then there is no z attribute on obj, but by searching its prototype chain, it is found that it is on foo.prototype, so obj.z=3, and for the first case, obj.valueOf() and toString are both on Object.prototype , so any object has these two attributes, because the prototype of any object is Object.prototype. Of course, except for the following special case,

var obj2 = Object.create(null);
obj2.valueOf(); //undefined
Copy after login

Object.create() creates an empty object, and the prototype of this object points to the parameter. The following comprehensive example shows you how to implement a class to inherit another class

//声明一个构造函数Person
function Person(name,age){
  this.name = name;
  this.age = age;
}
Person.prototype.hi = function (){
  console.log('Hi,my name is ' + this.name +',my age is '+this.age);
};
Person.prototype.LEGS_NUM=2;
Person.prototype.ARMS_NUM=2;
Person.prototype.walk = function (){
  console.log(this.name+' is walking !');
};
function Student(name,age,classNum){
  Person.call(this,name,age);
  this.classNum = classNum;
}
//创建一个空对象
Student.prototype = Object.create(Person.prototype);
//constructor指定创建一个对象的函数。
Student.prototype.constructor = Student;
Student.prototype.hi = function (){
  console.log('Hi,my name is ' + this.name +',my age is '+this.age+' and my class is '+this.classNum);
};
Student.prototype.learns = function (sub){
  console.log(this.name+' is learning '+sub);
};
//实例化一个对象Bosn
var Bosn = new Student('bosn',27,'Class 3');
Bosn.hi(); //Hi,my name is bosn,my age is 27 and my class is Class 3
Bosn.LEGS_NUM; //2
Bosn.walk(); //bosn is walking !
Bosn.learns('Math'); //bosn is learning Math

Copy after login

The this of the constructor Person and Student points to the instantiated object (Bosn), and the prototype of this object points to the prototype of the constructor.

We use the Object.create() method to create an empty object. The prototype of this object is Person.prototype. The advantage of writing this way is that we can create Studnet.prototype ourselves without affecting the Person.prototype property. Any attribute, and can inherit the original attributes on Person.prototype, because the subclass Student inherits the base class Person. If you directly write Person.prototype = Student.prototype, then they both point to the same object. When adding attributes to Student.prototype, the same attributes will be added to the prototype chain of Person.

For the call method in the constructor Student, this inside points to the instantiated object of the newly created Student, and inheritance is implemented through call.

Student.prototype.constructor = Student, the meaning of this sentence is to specify Student as the function that creates the Student.prototype object. If this sentence is not written, the function of the object is still Person.

For inheritance, there are three ways to implement it,

function Person(name,age){
  this.name = name;
  this.age = age;
}
function Student(){

}
Student.prototype = Person.prototype; //1
Student.prototype = Object.create(Person.prototype); //2
Student.prototype = new Person(); //3

Copy after login

The first one, as mentioned above, writing it directly like this will make the subclass and base class point to the bosn instance at the same time;

The second method avoids this point and implements inheritance well, letting the instance query the subclass first, and then query the base class if there is no corresponding attribute;

The third type, although inheritance is also implemented, calls the Person constructor. In this example, the constructor has two parameters name and age, but this third type does not pass anything and is not instantiated.

The above is the entire content of this article, I hope you all like it.

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.

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 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.

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

'Introduction to Object-Oriented Programming in PHP: From Concept to Practice' 'Introduction to Object-Oriented Programming in PHP: From Concept to Practice' Feb 25, 2024 pm 09:04 PM

What is object-oriented programming? Object-oriented programming (OOP) is a programming paradigm that abstracts real-world entities into classes and uses objects to represent these entities. Classes define the properties and behavior of objects, and objects instantiate classes. The main advantage of OOP is that it makes code easier to understand, maintain and reuse. Basic Concepts of OOP The main concepts of OOP include classes, objects, properties and methods. A class is the blueprint of an object, which defines its properties and behavior. An object is an instance of a class and has all the properties and behaviors of the class. Properties are characteristics of an object that can store data. Methods are functions of an object that can operate on the object's data. Advantages of OOP The main advantages of OOP include: Reusability: OOP can make the code more

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.

Java Interfaces and Abstract Classes: The Road to Programming Heaven Java Interfaces and Abstract Classes: The Road to Programming Heaven Mar 04, 2024 am 09:13 AM

Interface: An implementationless contract interface defines a set of method signatures in Java but does not provide any concrete implementation. It acts as a contract that forces classes that implement the interface to implement its specified methods. The methods in the interface are abstract methods and have no method body. Code example: publicinterfaceAnimal{voideat();voidsleep();} Abstract class: Partially implemented blueprint An abstract class is a parent class that provides a partial implementation that can be inherited by its subclasses. Unlike interfaces, abstract classes can contain concrete implementations and abstract methods. Abstract methods are declared with the abstract keyword and must be overridden by subclasses. Code example: publicabstractcla

C++ Function Inheritance Explained: How to Design a Good Base and Derived Class Inheritance Hierarchy? C++ Function Inheritance Explained: How to Design a Good Base and Derived Class Inheritance Hierarchy? May 03, 2024 am 11:06 AM

Function inheritance enables derived classes to inherit methods from base classes, enabling code reuse and polymorphism. Designing a good inheritance hierarchy following the single responsibility, open-closed, and Rees substitution principles can avoid code coupling and diamond problems.

See all articles