JavaScript的写类方式(2)
这篇开始会记录一些写类的工具函数,通过上篇我们知道本质上都是 构造函数+原型。理解了它碰到各式各样的写类方式就不惧怕了。
构造函数 + 原型 直接组装一个类;同一构造函数将组装出同一类型
1 2 3 4 5 6 7 8 9 10 11 | /** * $class 写类工具函数之一 * @param {Function} constructor * @param {Object} prototype */ function $ class (constructor, prototype) { var c = constructor || function (){}; var p = prototype || {}; c.prototype = p; return c; } |
用构造函数来生成类实例的属性(字段),原型对象用来生成类实例的方法。
1 2 3 4 5 6 7 8 9 10 11 12 | //构造函数 function Person(name) { this .name = name; } //原型对象 var proto = { getName : function (){ return this .name}, setName : function (name){ this .name = name;} } //组装 var Man = $ class (Person,proto); var Woman = $ class (Person,proto); |
这时候已经得到了两个类Man,Woman。并且是同一个类型的。测试如下:
1 2 | console.log(Man == Woman); //true console.log(Man.prototype == Woman.prototype); //true |
创建对象看看
1 2 3 4 5 6 7 | var man = new Man( "Andy" ); var woman = new Woman( "Lily" ); console.log(man instanceof Man); //true console.log(woman instanceof Woman); //true console.log(man instanceof Person); //true console.log(woman instanceof Person); //true |
ok,一切如我们所期望。但是有个问题,下面代码的结果输出false
1 | console.log(man.constructor == Person); //false |
这让人不悦:从以上的代码看出man的确是通过Man类new出来的 var man = new Man("Andy"),那么对象实例man的构造器应该指向Man,但为何事与愿违呢?
原因就在于工具函数重写了 Person 的原型:c.prototype = p;
好了,我们把 $class 稍微改写下,将方法都挂在构造器的原型上(而不是重写构造器的原型),如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | /** * $class 写类工具函数之一 * @param {Function} constructor * @param {Object} prototype */ function $ class (constructor, prototype) { var c = constructor || function (){}; var p = prototype || {}; // c.prototype = p; for ( var atr in p) { c.prototype[atr] = p[atr]; } return c; } |
相关:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
· 使用C#创建一个MCP客户端