Let you thoroughly understand the principles of Javascript inheritance!
The content this article brings to you is to help you thoroughly understand the principles of Javascript inheritance! It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Before understanding inheritance, you need to know three things about js:
What is the JS prototype chain
this What is the value
What does new in JS do
1. What is the JS prototype chain?
We know that JS has objects, such as
var obj = { name: 'obj' }
We print out obj through the console:
We will find that obj already has several properties (methods). Then the question comes: Where does valueOf / toString / constructor come from? We did not assign a value to obj.valueOf.
The above picture is a bit difficult to understand. I drew a schematic diagram by hand:
We found that the console typed The result is:
obj itself has an attribute name (this is what we added to it)
obj also has an attribute called __proto__ (It is an object)
obj also has an attribute, including valueOf, toString, constructor, etc.
obj.__proto__ actually also has one The attribute called __proto__ (console.log is not shown), the value is null
Now back to our question: Why does obj have these attributes valueOf / toString / constructor?
Answer: This is related to __proto__.
When we "read" obj.toString, the JS engine will do the following:
See if the obj object itself has a toString attribute. If not, go to the next step.
Look at whether the obj.__proto__ object has a toString attribute, and found that obj.__proto__ has a toString attribute, so I found it, so obj.toString is actually the obj.__proto__ found in step 2. .toString.
If obj.__proto__ does not exist, the browser will continue to view obj.__proto__.__proto__
If obj.__proto__.__proto__ also If not, the browser will continue to check obj.__proto__.__proto__.__proto__
proto is null.
The above process is the "search process" of "reading" attributes. And this "search process" is connected to the chain composed ofproto. This chain is called the "prototype chain".
Shared prototype chainNow we have another objectvar obj2 = { name: 'obj2' }As shown:
To put it bluntly, if we change one of them __proto__.toString, then the other one will actually change!
Just assign the value directly:
obj.toString = function(){ return '新的 toString 方法' }
- [Read] When properties are read, the prototype chain will be searched
- [New] When properties are added, the prototype chain will not be looked at
- 2. this What is the value of
You may have encountered this JS interview question:
var obj = { foo: function(){ console.log(this) } } var bar = obj.foo obj.foo() // 打印出的 this 是 obj bar() // 打印出的 this 是 window
Please explain why the values of the functions in the last two lines are different.
Function call
There are three function call forms in JS (ES5):
func(p1, p2) obj.child.method(p1, p2) func.call(context, p1, p2) // 先不讲 apply
Generally, beginners know the first two forms, and think that the first two forms " Better than the third form.
Our teacher Fang Fang’s grandma said that you must remember that the third calling form is the normal calling form:func.call(context, p1, p2)
The other two are syntax sugar and can be changed equivalently It is in the form of call:
func(p1, p2) is equivalent to func.call(undefined, p1, p2);
obj.child.method(p1, p2) is equivalent to obj .child.method.call(obj.child, p1, p2);
So far our function call has only one form:
func.call(context, p1, p2)In this way, this can be easily explained
This is the context above. This is the context passed when you call a function. Since you never use the call form of function call, you never know it.
Let’s first look at how to determine this in func(p1, p2):
当你写下面代码时 function func(){ console.log(this) } func() 等价于 function func(){ console.log(this) } func.call(undefined) // 可以简写为 func.call()
Logically speaking, the printed this should be undefined, but there is a rule in the browser:
如果你传的 context 就 null 或者 undefined,那么 window 对象就是默认的 context(严格模式下默认 context 是 undefined)因此上面的打印结果是 window。如果你希望这里的 this 不是 window,很简单:
func.call(obj) // 那么里面的 this 就是 obj 对象了
回到题目:
var obj = { foo: function(){ console.log(this) } } var bar = obj.foo obj.foo() // 转换为 obj.foo.call(obj),this 就是 obj bar() // 转换为 bar.call() // 由于没有传 context // 所以 this 就是 undefined // 最后浏览器给你一个默认的 this —— window 对象
[ ] 语法
function fn (){ console.log(this) } var arr = [fn, fn2] arr[0]() // 这里面的 this 又是什么呢?
我们可以把 arr0 想象为arr.0( ),虽然后者的语法错了,但是形式与转换代码里的 obj.child.method(p1, p2) 对应上了,于是就可以愉快的转换了:
arr[0]()
假想为 arr.0()
然后转换为 arr.0.call(arr)
那么里面的 this 就是 arr 了 :)
小结:
this 就是你 call 一个函数时,传入的第一个参数。
如果你的函数调用不是 call 形式, 请将其转换为 call 形式
三、JS 的 new 到底是干什么的?
我们声明一个士兵,具有如下属性:
var 士兵 = { ID: 1, // 用于区分每个士兵 兵种:"美国大兵", 攻击力:5, 生命值:42, 行走:function(){ /*走俩步的代码*/}, 奔跑:function(){ /*狂奔的代码*/ }, 死亡:function(){ /*Go die*/ }, 攻击:function(){ /*糊他熊脸*/ }, 防御:function(){ /*护脸*/ } }
我们制造一个士兵, 只需要这样:
兵营.制造(士兵)
如果需要制造 100 个士兵怎么办呢?
循环 100 次吧: var 士兵们 = [] var 士兵 for(var i=0; i<p>哎呀,看起来好简单</p><h4 id="质疑">质疑</h4><p>上面的代码存在一个问题:浪费了很多内存</p><ol class=" list-paddingleft-2"> <li><p>行走、奔跑、死亡、攻击、防御这五个动作对于每个士兵其实是一样的,只需要各自引用同一个函数就可以了,没必要重复创建 100 个行走、100个奔跑……</p></li> <li><p>这些士兵的兵种和攻击力都是一样的,没必要创建 100 次。</p></li> <li><p>只有 ID 和生命值需要创建 100 次,因为每个士兵有自己的 ID 和生命值。</p></li> </ol><h4 id="改进">改进</h4><p>通过第一节可以知道 ,我们可以通过原型链来解决重复创建的问题:我们先创建一个「士兵原型」,然后让「士兵」的 <strong>proto</strong> 指向「士兵原型」。</p><pre class="brush:php;toolbar:false">var 士兵原型 = { 兵种:"美国大兵", 攻击力:5, 行走:function(){ /*走俩步的代码*/}, 奔跑:function(){ /*狂奔的代码*/ }, 死亡:function(){ /*Go die*/ }, 攻击:function(){ /*糊他熊脸*/ }, 防御:function(){ /*护脸*/ } } var 士兵们 = [] var 士兵 for(var i=0; i<h4 id="优雅">优雅?</h4><p>有人指出创建一个士兵的代码分散在两个地方很不优雅,于是我们用一个函数把这两部分联系起来:</p><pre class="brush:php;toolbar:false">function 士兵(ID){ var 临时对象 = {}; 临时对象.__proto__ = 士兵.原型; 临时对象.ID = ID; 临时对象.生命值 = 42; return 临时对象; } 士兵.原型 = { 兵种:"美国大兵", 攻击力:5, 行走:function(){ /*走俩步的代码*/}, 奔跑:function(){ /*狂奔的代码*/ }, 死亡:function(){ /*Go die*/ }, 攻击:function(){ /*糊他熊脸*/ }, 防御:function(){ /*护脸*/ } } // 保存为文件:士兵.js 然后就可以愉快地引用「士兵」来创建士兵了: var 士兵们 = [] for(var i=0; i<p>JS 之父看到大家都这么搞,觉得何必呢,我给你们个糖吃,于是 JS 之父创建了 new 关键字,可以让我们少写几行代码:</p><p style="text-align: center;"><span class="img-wrap"><img src="/static/imghwm/default1.png" data-src="https://img.php.cn//upload/image/223/671/797/1538126235427481.png?x-oss-process=image/resize,p_40" class="lazy" title="1538126235427481.png" alt="Let you thoroughly understand the principles of Javascript inheritance!"></span></p><p><strong>只要你在士兵前面使用 new 关键字,那么可以少做四件事情:</strong></p><ol class=" list-paddingleft-2"> <li><p>不用创建临时对象,因为 new 会帮你做(你使用「this」就可以访问到临时对象);</p></li> <li><p>不用绑定原型,因为new 会帮你做(new 为了知道原型在哪,所以指定原型的名字 prototype);</p></li> <li><p>不用 return 临时对象,因为 new 会帮你做;</p></li> <li><p>不要给原型想名字了,因为 new 指定名字为 prototype。</p></li> </ol><h4 id="这一次用-new-来写">这一次用 new 来写</h4><pre class="brush:php;toolbar:false">function 士兵(ID){ this.ID = ID this.生命值 = 42 } 士兵.prototype = { 兵种:"美国大兵", 攻击力:5, 行走:function(){ /*走俩步的代码*/}, 奔跑:function(){ /*狂奔的代码*/ }, 死亡:function(){ /*Go die*/ }, 攻击:function(){ /*糊他熊脸*/ }, 防御:function(){ /*护脸*/ } } // 保存为文件:士兵.js 然后是创建士兵(加了一个 new 关键字): var 士兵们 = [] for(var i=0; i<p><strong>new 的作用,就是省那么几行代码。(也就是所谓的语法糖)</strong></p><h4 id="注意-constructor-属性">注意 constructor 属性</h4><p>new 操作为了记录「临时对象是由哪个函数创建的」,所以预先给「士兵.prototype」加了一个 constructor 属性:</p><pre class="brush:php;toolbar:false">士兵.prototype = { constructor: 士兵 }
如果你重新对「士兵.prototype」赋值,那么这个 constructor 属性就没了,所以你应该这么写:
士兵.prototype.兵种 = "美国大兵" 士兵.prototype.攻击力 = 5 士兵.prototype.行走 = function(){ /*走俩步的代码*/} 士兵.prototype.奔跑 = function(){ /*狂奔的代码*/ } 士兵.prototype.死亡 = function(){ /*Go die*/ } 士兵.prototype.攻击 = function(){ /*糊他熊脸*/ } 士兵.prototype.防御 = function(){ /*护脸*/ }
或者你也可以自己给 constructor 重新赋值:
士兵.prototype = { constructor: 士兵, 兵种:"美国大兵", 攻击力:5, 行走:function(){ /*走俩步的代码*/}, 奔跑:function(){ /*狂奔的代码*/ }, 死亡:function(){ /*Go die*/ }, 攻击:function(){ /*糊他熊脸*/ }, 防御:function(){ /*护脸*/ } }
四、继承
继承的本质就是上面的讲的原型链
1)借助构造函数实现继承
function Parent1() { this.name = 'parent1'; } Parent1.prototype.say = function () {} function Child1() { Parent1.call(this); this.type = 'child'; } console.log(new Child1);
打印结果:
这个主要是借用call 来改变this的指向,通过 call 调用 Parent ,此时 Parent 中的 this 是指 Child1。有个缺点,从打印结果看出 Child1并没有say方法,所以这种只能继承父类的实例属性和方法,不能继承原型属性/方法。
2)借助原型链实现继承
/** * 借助原型链实现继承 */ function Parent2() { this.name = 'parent2'; this.play = [1, 2, 3]; } function Child2() { this.type = 'child2'; } Child2.prototype = new Parent2(); console.log(new Child2); var s1 = new Child2(); var s2 = new Child2();
打印:
通过一讲的,我们知道要共享莫些属性,需要 对象.__proto__ = 父亲对象的.prototype,但实际上我们是不能直接 操作__proto__,这时我们可以借用 new 来做,所以
Child2.prototype = new Parent2(); Child2.prototype.__proto__ = Parent2.prototype; 这样我们借助 new 这个语法糖,就可以实现原型链继承。但这里有个总是,如打印结果,我们给 s1.play新增一个值 ,s2 也跟着改了。所以这个是原型链继承的缺点,原因是 s1.__pro__ 和 s2.__pro__指向同一个地址即 父类的prototype。
3)组合方式实现继承
/** * 组合方式 */ function Parent3() { this.name = 'parent3'; this.play = [1, 2, 3]; } Parent3.prototype.say = function () { } function Child3 () { Parent3.call(this); this.type = 'child3'; } Child3.prototype = new Parent3(); var s3 = new Child3(); var s4 = new Child3(); s3.play.push(4); console.log(new Child3); console.log(s3.play, s4.play)
打印:
将 1 和 2 两种方式组合起来,就可以解决1和2存在问题,这种方式为组合继承。这种方式有点缺点就是我实例一个对象的时, 父类 new 了两次,一次是var s3 = new Child3()对应 Child3.prototype = new Parent3()还要new 一次。
4)组合继承的优化1
function Parent4() { this.name = 'parent4'; this.play = [1, 2, 3]; } Parent4.prototype.say = function () { } function Child4() { Parent4.call(this); this.type = 'child4'; } Child4.prototype = Parent4.prototype; var s5 = new Child4(); var s6 = new Child4();
这边主要为 Child4.prototype = Parent4.prototype, 因为我们通过构造函数就可以拿到所有属性和实例的方法,那么现在我想继承父类的原型对象,所以你直接赋值给我就行,不用在去 new 一次父类。其实这种方法还是有问题的,如果我在控制台打印以下两句:
从打印可以看出,此时我是没有办法区分一个对象 是直接 由它的子类实例化还是父类呢?我们还有一个方法判断来判断对象是否是类的实例,那就是用 constructor,我在控制台打印以下内容:
咦,你会发现它指向的是父类 ,这显然不是我们想要的结果, 上面讲过我们 prototype里面有一个 constructor, 而我们此时子类的 prototype 指向是 父类的 prototye ,而父类prototype里面的contructor当然是父类自己的,这个就是产生该问题的原因。
组合继承的优化2
/** * 组合继承的优化2 */ function Parent5() { this.name = 'parent4'; this.play = [1, 2, 3]; } Parent5.prototype.say = function () { } function Child5() { Parent5.call(this); this.type = 'child4'; } Child5.prototype = Object.create(Parent5.prototype);
这里主要使用Object.create(),它的作用是将对象继承到__proto__属性上。举个例子:
var test = Object.create({x:123,y:345}); console.log(test);//{} console.log(test.x);//123 console.log(test.__proto__.x);//3 console.log(test.__proto__.x === test.x);//true
那大家可能说这样解决了吗,其实没有解决,因为这时 Child5.prototype 还是没有自己的 constructor,它要找的话还是向自己的原型对象上找最后还是找到 Parent5.prototype, constructor还是 Parent5 ,所以要给 Child5.prototype 写自己的 constructor:
Child5.prototype = Object.create(Parent5.prototype); Child5.prototype.constructor = Child5;
The above is the detailed content of Let you thoroughly understand the principles of Javascript inheritance!. For more information, please follow other related articles on the PHP Chinese website!

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

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

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 Chinese version
Chinese version, very easy to use