Table of Contents
Inherited method
Use different methods to create objects and generate prototype chains
Objects created by syntax structures
Objects created by constructors
Performance
Home Web Front-end JS Tutorial JavaScript inheritance and prototype chain

JavaScript inheritance and prototype chain

Mar 19, 2018 pm 05:16 PM
javascript js inherit

This time I will bring you JavaScript inheritance and prototype chain. What are the precautions when using JavaScript inheritance and prototype chain? The following is a practical case, let’s take a look. .

I have been watching WeChat mini-programs recently. In the afternoon, I changed my appetite and took a look at the prototype chain inheritance of js to supplement the basics of js

JavaScript ObjectThere is a chain pointing to a prototype object. When trying to access the properties of an object, he will not only search on the object, but also search for the prototype of the object, and the prototype of the prototype of the object, and search layer by layer. Until a property with a matching name is found or the end of the prototype chain is reached

1

// 让我们假设我们有一个对象 o, 其有自己的属性 a 和 b:// {a: 1, b: 2}// o 的 [[Prototype]] 有属性 b 和 c:// {b: 3, c: 4}// 最后, o.[[Prototype]].[[Prototype]] 是 null.// 这就是原型链的末尾,即 null,// 根据定义,null 没有[[Prototype]].// 综上,整个原型链如下: // {a:1, b:2} ---> {b:3, c:4} ---> nullconsole.log(o.a); // 1// a是o的自身属性吗?是的,该属性的值为1console.log(o.b); // 2// b是o的自身属性吗?是的,该属性的值为2// 原型上也有一个'b'属性,但是它不会被访问到.这种情况称为"属性遮蔽 (property shadowing)"console.log(o.c); // 4// c是o的自身属性吗?不是,那看看原型上有没有// c是o.[[Prototype]]的属性吗?是的,该属性的值为4console.log(o.d); // undefined// d是o的自身属性吗?不是,那看看原型上有没有// d是o.[[Prototype]]的属性吗?不是,那看看它的原型上有没有// o.[[Prototype]].[[Prototype]] 为 null,停止搜索// 没有d属性,返回undefined

Copy after login

Inherited method

When the inherited function is called, this points to the current inheritance object, rather than the prototype object where the inherited function resides.

1

2

3

4

5

var o = {

  a: 2,

  m: function(){

    return this.a + 1;

  }};console.log(o.m()); // 3// 当调用 o.m 时,'this'指向了o.var p = Object.create(o);// p是一个继承自 o 的对象p.a = 4; // 创建 p 的自身属性 aconsole.log(p.m()); // 5// 调用 p.m 时, 'this'指向 p. // 又因为 p 继承 o 的 m 函数// 此时的'this.a' 即 p.a,即 p 的自身属性 'a'

Copy after login

Use different methods to create objects and generate prototype chains

Objects created by syntax structures

1

2

var o = {a: 1};// o 这个对象继承了Object.prototype上面的所有属性// o 自身没有名为 hasOwnProperty 的属性// hasOwnProperty 是 Object.prototype 的属性// 因此 o 继承了 Object.prototype 的 hasOwnProperty// Object.prototype 的原型为 null// 原型链如下:// o ---> Object.prototype ---> nullvar a = ["yo", "whadup", "?"];// 数组都继承于 Array.prototype // (Array.prototype 中包含 indexOf, forEach等方法)// 原型链如下:// a ---> Array.prototype ---> Object.prototype ---> nullfunction f(){

  return 2;}// 函数都继承于Function.prototype// (Function.prototype 中包含 call, bind等方法)// 原型链如下:// f ---> Function.prototype ---> Object.prototype ---> null

Copy after login

Objects created by constructors

In JavaScript, a constructor is actually an ordinary function. When the new operator is used to act on this function, it can be called a constructor (constructor).

1

2

3

4

5

6

7

8

9

10

11

12

function Graph() {

  this.vertices = [];

  this.edges = [];

}

Graph.prototype = {

  addVertex: function(v){

    this.vertices.push(v);

  }

};

var g = new Graph();

// g是生成的对象,他的自身属性有'vertices'和'edges'.

// 在g被实例化时,g.[[Prototype]]指向了Graph.prototype.

Copy after login

Object.create Created objects

A new method was introduced in ECMAScript 5: Object.create(). This method can be called to create a new object. The prototype of the new object is the first parameter passed in when calling the create method:

1

var a = {a: 1}; // a ---> Object.prototype ---> nullvar b = Object.create(a);// b ---> a ---> Object.prototype ---> nullconsole.log(b.a); // 1 (继承而来)var c = Object.create(b);// c ---> b ---> a ---> Object.prototype ---> nullvar d = Object.create(null);// d ---> nullconsole.log(d.hasOwnProperty); // undefined, 因为d没有继承Object.prototype

Copy after login

class The object created by the keyword

Introduced by ECMAScript6 A new set of keywords are used to implement classes. These constructs will be familiar to developers using class-based languages, but they are different. JavaScript is still based on prototypes. These new keywords include class, constructor, static, extends and super.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

"use strict";class Polygon {

  constructor(height, width) {

    this.height = height;

    this.width = width;

    console.log(height)    //2

  }}class Square extends Polygon {

  constructor(sideLength) {

    super(sideLength, sideLength);

  }

  get area() {

    return this.height * this.width;

  }

  set sideLength(newLength) {

    this.height = newLength;

    this.width = newLength;

  }}var square = new Square(2);

Copy after login

Performance

1

2

3

4

5

6

function Graph() {

  this.vertices = [];

  this.edges = [];}Graph.prototype = {

  addVertex: function(v){

    this.vertices.push(v);

  }};var g = new Graph();console.log(g.hasOwnProperty('vertices'));// trueconsole.log(g.hasOwnProperty('nope'));// falseconsole.log(g.hasOwnProperty('addVertex'));// falseconsole.log(g.proto.hasOwnProperty('addVertex'));// true

Copy after login

hasOwnProperty is the only way in JavaScript to handle properties without traversing the prototype chain.

So when you execute:

1

var o = new Foo();

Copy after login

JavaScript actually executes (or something like this):

1

2

3

var o = new Object();

o._proto_ = Foo.prototype;

Foo.call(0)

Copy after login

1

o.someProp;

Copy after login

It checks o Whether it has someProp attribute.

If not, it will look for Object.getPrototypeOf(o).someProp,

If still not, it will continue to look for Object.getPrototypeOf(Object. getPrototypeOf(o)).someProp.

ps:

Object.getPrototypeOf() method returns the prototype of the specified object (the value of the internal [[Prototype]] attribute ).

1

2

3

4

var proto = {};

var obj = Object.create(proto);

var a= Object.getPrototypeOf(obj)

console.log(a); {}

Copy after login

If you think it is good, please visit MDN

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

What class definition components are there in React

ajax study notes

The above is the detailed content of JavaScript inheritance and prototype chain. For more information, please follow other related articles on the PHP Chinese website!

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)

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

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.

The relationship between js and vue The relationship between js and vue Mar 11, 2024 pm 05:21 PM

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

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

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.

'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

js method to refresh current page js method to refresh current page Jan 24, 2024 pm 03:58 PM

js methods to refresh the current page: 1. location.reload(); 2. location.href; 3. location.assign(); 4. window.location. Detailed introduction: 1. location.reload(), use the location.reload() method to reload the current page; 2. location.href, you can refresh the current page by setting the location.href attribute, etc.

See all articles