Home Web Front-end JS Tutorial Detailed explanation of prototype-based inheritance features in JavaScript_Basic knowledge

Detailed explanation of prototype-based inheritance features in JavaScript_Basic knowledge

May 16, 2016 pm 03:02 PM
javascript prototype inherit

Inheritance in JavaScript is rather weird. Interface inheritance cannot be implemented and can only rely on prototypal inheritance.

Prototype Chain
A prototype is an object. The instance created through the constructor will have a pointer pointing to the prototype to obtain the properties and methods of the prototype. In this way, the instance object has the attribute methods of the constructor and the attribute methods of the prototype. Then point the prototype of the constructor that needs to be inherited to this instance, and you can have all the attribute methods of this instance to achieve inheritance.
Look at the demo code below:

//声明超类,通过构造函数和原型添加有关属性和方法
function Super(){
  this.property = true;
}
Super.prototype.getSuperValue = function() {
  return this.property;
};

//声明子类的构造函数
function SubType() {
  this.subproperty = false;
}
//将子类的原型指向超类的实例,得到超类的一切
SubType.prototype = new Super();
SubType.prototype.constructor = SubType;
SubType.prototype.getSubValue = function(){
  return this.subproperty;
};
//由子类创建对象,测试是否继承超类方法和属性
var instance = new SubType();
console.log(instance.getSuperValue());

Copy after login

The default prototype of all functions is an instance of Object, so the default prototype will contain an internal pointer pointing to Object.prototype.
Use instanceof and isPrototypeOf to determine the relationship between prototype and instance:

instance instanceof Object;
Object.prototype.isPrototypeOf(instance);
Copy after login

When using the prototype chain, you need to define the method carefully. If a subclass needs to override a method or extension of the supertype, it must be placed after the statement that replaces the prototype, so that it can take effect. In addition, when implementing inheritance through the prototype chain, you cannot use object literals to create prototype methods, which will override the prototype chain:

......
SubType.prototype = new Super();
SubType.prototype = {
  ....
};
Copy after login

This will replace the pointer pointing to the new object, thus rewriting the prototype chain.
The inheritance method of the prototype chain is flawed. There are two main problems:
1. From a prototype containing a reference type value, it will be shared by all instances.
As mentioned in the previous article, prototype properties containing reference type values ​​will be shared by all instances. If one instance is modified, other instances will change accordingly, so the properties need to be defined in the constructor. When inheriting through the prototype chain, no matter whether the attributes in the super class are defined in the constructor or the prototype, they all become instance objects and are inherited by the subclass, thus affecting the instances of the subclass.
2. When creating an instance of a subtype, parameters cannot be passed to the constructor of the supertype.
Inheritance of the prototype chain directly points the subclass prototype to the instance of the superclass. At this time, parameters can be passed to the superclass. But when a subclass creates an instance, parameters can only be passed to the constructor of the subclass, but not to the constructor of the superclass.
Therefore, in actual applications, the prototype chain is rarely used alone.

Some related coding practices

Identify a prototype attribute

function hasPrototypeProperty(object, name) {
  return name in object && !object.hasOwnProperty(name);
}
Copy after login

Use prototype objects in constructors

function Person(name) {
  this.name = name;
}

Person.prototype = {
  constructor: Person,
  sayName: function () {
    console.log(this.name);
  },
  toString: function() {

  }
};

var person1 = new Person('Nicholas');
var person2 = new Person('Greg);

console.log(person1 instanceof Person); // true
console.log(person1.constructor === Person); // true
console.log(person1.constructor === Object); // false

console.log(person2 instanceof Person); // true
console.log(person2.constructor === Person); // true
console.log(person2.constructor === Object); // false

Copy after login

Object inheritance

var person1 = {
  name: 'Nicholas',
  sayName: function () {
    console.log(this.name);
  }
};

var person2 = Object.create(person1, {
  name: {
    configurable: true,
    enumerable: true,
    value: 'Greg',
    writable: true
  }
});

person1.sayName(); // Nicholas
person2.sayName(); // Greg

console.log(person1.hasOwnProperty('sayName')); // true
console.log(person1.isPropertyOf(person2)); // true
console.log(person2.hasOwnProperty('sayName')); // false

Copy after login

Module Mode

var person = (function () {
  var age = 25;

  function getAge() {
    return age;
  }

  function growOlder() {
    age++;
  }

  return {
    name: 'Nicholas',
    getAge: getAge,
    growOlder: growOlder
  };
}());

Copy after login

Scope constructor

function Person(name) {
  this.name = name;
}

Person.prototype.sayName = function() {
  console.log(this.name);
};

var person1 = Person('Nicholas');

console.log(person1 instanceof Person); // false
console.log(typeof person1); // undefined
console.log(name); // Nicholas

Copy after login
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
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 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.

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.

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.

Introduction to the new map of Genshin Impact version 4.4 Introduction to the new map of Genshin Impact version 4.4 Jan 31, 2024 pm 06:36 PM

Introducing the new map of Genshin Impact version 4.4. Friends, Genshin Impact 4.4 version also ushered in the Sea Lantern Festival in Liyue. At the same time, a new map area will be launched in version 4.4 called Shen Yu Valley. According to the information provided, Shen Yugu is actually part of Qiaoying Village, but players are more accustomed to calling it Shen Yugu. Now let me introduce the new map to you. Introduction to the new map of Genshin Impact version 4.4. Version 4.4 will open "Chenyu Valley·Shanggu", "Chenyu Valley·Nanling" and "Laixin Mountain" in the north of Liyue. Teleportation anchor points have been opened for travelers in "Chenyu Valley·Shanggu" . ※After completing the prologue of the Demon God Quest·Act 3: The Dragon and the Song of Freedom, the teleportation anchor point will be automatically unlocked. 2. Qiaoyingzhuang When the warm spring breeze once again caressed the mountains and fields of Chenyu, the fragrant

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

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

See all articles