
javascript 继承 -自己动手实践
发布日期:2021-05-09 04:22:23
浏览次数:15
分类:博客文章
本文共 1942 字,大约阅读时间需要 6 分钟。
javascript 继承 , 老生长谈的东西, 大家应该都很熟悉了, 平时工作基本不会直接使用, 这段时间不忙, 所以补习了下相关基础知识 ,自己动手实践, 加深理解:
基类定义如下:
// base class function Animal(t) { if(typeof t==='string') this.type=t; else { if(t) this.type=t.toString(); else this.type='Animal' } this.speak=function(str) { if(str) console.log(this.type+' said '+str); else throw "please specify what you want to say!"; } }
1.原型继承 (javascript 类库本身基于原型继承)
String, Number , Boolean 这三大原始类型 我们可以很直接的通过prototype 检查到他们继承自Object.
Date, RegExp ,Array 这三应该是间接继承了Object, 他们的prototype属性很特殊 :
Date.prototype =Invalid Date
RegExp.prototype=/(?:)/
Array.prototype=[]
原型继承代码如下: (可以看到Mokey 原型链上的Animal和Object)
// Monkey : Animal function Monkey(name,age) { this.name=name; this.age=age; } Monkey.prototype=new Animal('Monkey'); // Example 01 var m=new Monkey('codeMonkey',10); /* Monkey: age: 10 name: "codeMonkey" __proto__: Animal speak: function (str) type: "Monkey" __proto__: Animal constructor: function Animal(t) __proto__: Object */ console.log(m.type); // Monkey console.log(m.name); // codeMonkey console.log(m.age); // 10 m.speak('hello world') // Monkey said hello world
2. 调用父类构造函数 ( 通过传递子类的this指针 , 将原本是父类的公开成员直接添加到了子类中,从子类原型链中无法看出继承关系)
// Human:Animal function Human(id,name) { // call base class's constuctor function Animal.call(this,'Human'); this.id=id; this.name=name; } var h=new Human(1,'leon'); /* id: 1 name: "leon" speak: function (str) type: "Human" __proto__: Human constructor: function Human(id,name) __proto__: Object */ h.speak('hello world'); // Human said hello world console.log(h.type); // Human
发表评论
最新留言
路过按个爪印,很不错,赞一个!
[***.219.124.196]2025年04月04日 03时20分10秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
说说字库和字模的故事,然后在 MaixPy 里实现打印中文字体(任意字体)吧!
2019-03-06
线性代数应该这样学9:上三角矩阵、对角矩阵
2019-03-06
【科学计算】插值理论
2019-03-06
centos7一步一步搭建docker jenkins 及自定义访问路径重点讲解
2019-03-06
深度学习一:深度前馈网络和反向传播
2019-03-06
在wxPython使ListCtrl占据整个窗口
2019-03-06
微软面试题
2019-03-06
Google新玩法(转载)
2019-03-06
C#中Dispose和Close的区别!
2019-03-06
如何让服务在流量暴增的情况下保持稳定输出
2019-03-06
一个20年技术老兵的 2020 年度技术总结
2019-03-06
一例完整的websocket实现群聊demo
2019-03-06
SQLSERVER数据库死锁与优化杂谈
2019-03-06
【Net】ABP框架学习之它并不那么好用
2019-03-06
Git 笔记
2019-03-06
Harbor 批量清理历史镜像
2019-03-06
使用Azure Functions玩转Serverless
2019-03-06
.NET Core 基于Websocket的在线聊天室
2019-03-06
使用MySQL Shell创建MGR
2019-03-06