


Inheritance analysis through prototype chain in javascript (code attached)
The content of this article is about the analysis of inheritance through the prototype chain in JavaScript (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Prototype and prototype chain
The prototype prototype will be automatically generated when creating a new function, and there will also be a constructor in the prototype, which refers back to the function object that created the prototype.
__proto__ is the [[prototype]] built into the object or instance, which points to the prototype of the object that generated the object. __proto__ is provided in the browser so that we can access it through __proto_ A chain formed by the pointing of _ is called a prototype chain. The entire link of the prototype chain is: Instance object- -> prototype of constructor- ->Prototype of Object- ->null .
When we access the properties or methods of an object, we first search from this object. If the property or method does not exist in this object, we will search upward along the prototype chain until we find the property or method. Or stop when null is reached.
This also explains why there are no push, pop, shift, unshift and other methods on the array object, but you can access
constructor
The constructor attribute points to the function that generates ( Object) function (object), such as
var a = function(){}; var b = new a(); var c = {}; var d = []; //以下皆为true console.log(b.constructor === a) //因为实例b是由构造函数产生的 console.log(a.constructor === Function)//函数a实际是Function的实例,同理 console.log(c.constructor === Object)//空对象c是Object的实例 console.log(d.constructor === Array)//空对象c是Object的实例 console.log(Object.constructor === Function)//Object自身就是一个构造函数,同理 console.log(Array.constructor === Function)//Array自身也是一个构造函数 //--------------------------------------------------------------- //首先__proto__指向的是产生该对象的对象的prototype, //也即a.prototype,prototype中也的constructor,回指创建该prototype的函数对象,也即函数a console.log(b.__proto__.constructor === a)
By the way, instanceof, A instanceof B is to find the prototype of B in the prototype chain of A, and it returns true if it is found. Return false
//有个奇怪的现象,下面都返回true,这是为什么呢? //因为JS中一切都继承自Object,除了最顶层的null, //所以在Function的原型链中能找到Object.prototype console.log(Function instanceof Object) //而Object自身就是一个构造函数,因此在Object的原型链中也能找到Function.prototype console.log(Object instanceof Function)
Inheritance through the prototype chain
From the above analysis, we can use the prototype chain to implement the logic of inheritance. Inheritance is a very important concept in object-oriented
function Dog(name){ this.name = name; this.say1 = function(){ console.log(this.name) } } Dog.prototype.say2 = function(){ console.log(this.name) } Dog.prototype.test = 1 //say本来应该是所有Dog实例的共有方法, //如果放在构造函数中,那么就会导致没办法数据共享,每一个实例都有自己的属性和方法的副本,这是对资源的极大浪费 //如果放在Dog.prototype中,那么利用原型链的特性,就可以让所有实例共用一个方法, //需要注意的是,由于共用了一个方法,对属性的更改是对所有实例透明的 var dog1 = new Dog('lalala'); let dog2 = new Dog('wahaha'); dog1.test++;//2 dog2.test++;//3 console.log(dog1.say1 === dog2.say1)// false console.log(dog1.say2 === dog2.say2)// true //现在,我们可以尝试着去实现继承了 //我们是通过原型链去实现继承的, //之前的原型链是:Dog实例 --> Dog函数 --> Object --> null //那么现在的原型链需要改成 Dog实例 --> Dog函数 --> Dog父类(Animal函数) --> Object --> null //第一种方案,改变Dog函数的prototype,让他指向Animal的实例 function Animal(){ this.species = 'unknown'; } Dog.prototype = new Animal(); //这里改变后会导致prototype中的constructor改变 Dog.prototype.constructor = Dog; //第二钟方案,改变Dog函数的prototype,让他指向Animal的prototype function Animal(){} Animal.prototype.species = 'unknown'; Dog.prototype = Animal.prototype; //这里改变后会导致prototype中的constructor改变 Dog.prototype.constructor = Dog; //第三种方案,调用apply或call,将Animal的this绑定到Dog中 function Animal(){ this.species = 'unknown'; } function Dog(name){ Animal.apply(this, arguments); this.name = name; } //第四种方法,通过Object.create()方法实现继承,过滤掉了父类实例属性,Dog.prototype中就没有了Animal的实例化数据了 //这种方法也是ES6中Class被babel编译成ES5所用的方法 function Animal(){ this.species = 'unknown'; } function Dog(name){ Animal.apply(this, arguments); this.name = name; } //这里模拟了 Dog.prototype = Object.create(Animal.prototype) var f = function(){}; f.prototype = Animal.pototype; Dog.prototype = new f(); Dog.__proto__ = Animal; //这里改变后会导致prototype中的constructor改变 Dog.prototype.constructor = Dog; //现在就能访问到Animal中的species属性了 var dog = new Dog('lalala'); dog.species;//unknown
The above are some methods of using the prototype chain to achieve inheritance
ES6 class class
With the above knowledge, we can study the ES6 class class, this syntactic sugar It makes it easier for us to implement classes and inheritance. It provides keywords such as extends, static, and super.
//这是es6的代码实现 class Parent { static l(){ console.log(222) } constructor(m){ this.m = m } get(){ return this.m; } } class Child extends Parent { constructor(n){ super(4); this.n = n; } get(){ return this.n } set(a){ this.n = a; } } //这是利用babel编译之后的es5的实现 //_createClass是一个自执行函数,作用给构造函数绑定静态方法和动态方法 //对于静态的static关键字声明的变量,会直接绑定在函数对象上,作为静态属性(方法) //对于在class中声明的函数方法,则会绑定在构造函数的prototype上,通过Object.definePropety方法 var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i <h2 id="Summary">Summary</h2>
Through the above analysis, the prototype and prototype I have a deeper and clearer understanding of the chain, and I am also familiar with the usage of constructor and instanceof. I have deepened my understanding of the inheritance method based on the prototype chain and clarified this piece of knowledge.
In the analysis of the source code of ES6 classes compiled by babel, we also learned about the usage of Object.create and Object.setPrototypeOf, and explored how to simulate super, extends and static realization.
Related recommendations:
JavaScript object-oriented - inheritance based on prototype chain
JavaScript Inheritance and prototype chain
The above is the detailed content of Inheritance analysis through prototype chain in javascript (code attached). For more information, please follow other related articles on the PHP Chinese website!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

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

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software