原型继承和 Class 继承
25-04-07 04:48
561
0
⾸先先来讲下 class ,其实在 JS 中并不存在类, class 只是语法糖,本质还是函数
class Person {} Person instanceof Function; // true
组合继承
function Parent(value) { this.val = value; } Parent.prototype.getValue = function () { console.log(this.val); }; function Child(value) { Parent.call(this, value); } Child.prototype = new Parent(); const child = new Child(1); child.getValue(); // 1 child instanceof Parent; // true
以上继承的⽅式核⼼是在⼦类的构造函数中通过 Parent.call(this) 继承⽗类的属性, 然后改变⼦类的原型为 new Parent() 来继承⽗类的函数。 这种继承⽅式优点在于构造函数可以传参,不会与⽗类引⽤属性共享,可以复⽤⽗类的函 数,但是也存在⼀个缺点就是在继承⽗类函数的时候调⽤了⽗类构造函数,导致⼦类的原 型上多了不需要的⽗类属性,存在内存上的浪费
寄⽣组合继承
这种继承⽅式对组合继承进⾏了优化,组合继承缺点在于继承⽗类函数时调⽤了构造函数,我们只需要优化掉这点就⾏了
function Parent(value) { this.val = value; } Parent.prototype.getValue = function () { console.log(this.val); }; function Child(value) { Parent.call(this, value); } Child.prototype = Object.create(Parent.prototype, { constructor: { value: Child, enumerable: false, writable: true, configurable: true, }, }); const child = new Child(1); child.getValue(); // 1 child instanceof Parent; // true
class继承
class Parent { constructor(value) { this.val = value; } getValue() { console.log(this.val); } } class Child extends Parent { constructor(value) { super(value); this.val = value; } } let child = new Child(1); child.getValue(); // 1 child instanceof Parent; // true
-
Zend推出新开发套件 PHP码农也能开发iOS应用
不久之前,Zend首席执行官Andi Gutmans对外发布了PHP开发套件Zend Studio 10(目前还属于Beta阶段)。新的套件使得PHP编程人员可以用自己熟悉的语言在移动平台下打造应用程序(编者注:原文作者用的是native moblie app,但是我到Zend官网了解了一下,他们的移动应用方案是基于 HTML5+ JavaScript+ PHP的)。 1026 0 21-04-07 -
2012计算机 信息技术专业教师招聘资料
【豆丁★教育百科】'初中信息技术教师招聘考试试题',doc_type,doc.doc【豆丁★教育百科】08年云南省特岗小学信息技术教师招聘考试... 1249 0 24-08-20 -
html上传图片
343 0 21-06-02 -
微擎系统智慧快递 v2.5.35 模块
智慧快递V2.5.35全解密安装更新包,新增自定义电子面单!只服务于小型快递快件的分发机制,极大的缩短的人工成本录入快递流程(PC和手机端... 1300 0 24-05-24 -
教师资格证面试初中
中公资格证面试-初中体育试讲+答辩讲义(K.整理).pdf中公资格证面试-初中体育试讲示范讲义(K.整理).pdf中公资格证面试-初中体育题本梳理... 1102 0 24-08-19 -
3 大主流系统框架:由浅入深分析 Expre、Koa 和 Egg.j
3 大主流系统框架:由浅入深分析 Expre、Koa 和 Egg.j介绍一些目前主流框架的设计思想,同时介绍其核心代码部分的实现,为后续使用框架... 1078 0 24-05-24 -
php读取文件夹图片
<?php $dir = './images/'; if( isset($_GET['path']) ){ $dir = $dir."/".trim($_GET['path']); } if( isset($_... 355 0 21-06-02 -
微擎 v2.5.7 纯净版框架+人人商城V3 3.10.18 完整版+人人3.11.1小程序前端+后端
微擎是一款开源的微信公众号,小程序,支付宝小程序,熊掌号,pc建站管理系统,基于目前最流行的WEB2.0的架构(php+mysql),拥有成熟、稳... 575 0 21-07-02
发表我的评论
共0条评论
- 这篇文章还没有收到评论,赶紧来抢沙发吧~