当前位置:网站首页>JS-寄生组合式继承
JS-寄生组合式继承
2022-07-27 11:02:00 【大鲤余】
原型继承
child.prototype=new Parent()
function A(x){
this.x=x
}
A.prototype.getX=function(){
console.log(this.x)}
function B(y){
this.y=y
}
B.prototype.gety=function(){
console.log(this.y)}
B.prototype=new A()
B.prototype.constructor=B//由于B的原型对象指向A的实例了,那么其构造器就会指向A,因此要改一下原型对象中构造器的指向
让子类的原型指向父类的实例,父类的实例的原型链会指向类的原型.这个方式有很大的缺点:当修改子类实例父类实例也会发生变化,因为这里是使用引用的方式,即在同一个内存空间里操作
Object.create()
创建一个新对象,使用现有的对象来提供新创建的对象的__proto__
即给你的对象提供一个__proto__
继承组合式继承方式
是用call继承和Object.create
function Person(name){
this.name=name
}
function A(sex){
Person.call(this,'A extends Person')
this.sex=sex
}
Person.prototype.getName=function(){
console.log(this.name)
}
A.prototype=Object.create(Person.prototype)
A.prototype.constructor=A
call继承的目的在于将Person的私有属性继承为自己的私有属性,接下来的每个A的实例都会有一个私有属性name=’A extends Person‘,但只用call继承还不够,我们在这里将父构造函数当普通方法调用了,但无法拿到父类原型对象上的属性和方法。因此我们需要将子类原型指向父类的原型。这样给A的prototype原型对象提供了Person.prototype,这样A的实例的__proto__指向A的prototype,A的prototype的__proto__指向Person的prototype。这种组合式继承即拿到了父类的私有属性和方法成为自己的私有属性方法,也拿到了父类公有的属性和方法。是在es6继承之前的最佳方式
图里的A就是Person父类
边栏推荐
- C programming language (2nd Edition) -- Reading Notes -- 1.4
- 局域网SDN技术硬核内幕 12 云网CP的日常恩爱——硬件VXLAN转发平面
- Maker paper data search training notes
- C programming language (2nd Edition) -- Reading Notes -- 1.5.4
- Tlc549proteus simulation &sallen key filter &ad736vrms to DC conversion &proteus view 51 register value
- C programming language (2nd Edition) -- Reading Notes -- 1.5.2
- Principle of PWM and generation of PWM wave
- TapNet: Multivariate Time Series Classification with Attentional Prototypical Network
- LAN SDN technology hard core insider 11 the key of cloud convergence CP -- hierarchical port binding
- The C programming language (2nd) -- Notes -- 1.10
猜你喜欢

PWM的原理和PWM波的产生

暂用 Solo,博客选择困难

makefile模板

shell编程之免交互

Japan Fukushima waste dump safety monitoring agreement will recognize the "safety" of the sea discharge plan

VSCode复制代码时去掉样式/语法高亮/代码高亮/黑色背景

【Unity入门计划】CreatorKitFPS:第一人称射击3D小游戏

Why choose smart TV?

Weibo comment crawler + visualization

Principle of PWM and generation of PWM wave
随机推荐
How to make a graph? Multiple subgraphs in a graph are histogram (or other graphs)
C programming language (2nd Edition) -- Reading Notes -- 1.5.1
[untitled] multimodal model clip
Beyond compare 3 next difference segment / down search arrow not found
多种进制之间的转换
Common power supply problems and solutions of Arduino
Moveit2 -- 2. Quick start of moveit in rviz
希腊字母读法
JUC框架 从Runnable到Callable到FutureTask 使用浅析
STM32 compilation error: l6235e: more than one section matches selector - cannot all be first/l
Wilcoxon rank-sum 和 signed-rank
Local virtual machine initialization script
一些MathType常用快捷键
第8章 多线程
局域网SDN技术硬核内幕 12 云网CP的日常恩爱——硬件VXLAN转发平面
Newton-Raphson迭代法
Shell脚本文本三剑客之sed
Greek alphabet reading
LAN SDN hard core technology insider 23 looking forward to the future - RDMA (Part 1)
w.r.t. ; i.e.;etc.;e.g.是什么意思