理想的继承范式——寄生组合式继承

复制代码
 1 window.onload = function() {
 2     var person1 = new SubType("Gee", 20);
 3     var person2 = new SubType("Key", 21);
 4 
 5     person1.colors.push("yellow");
 6     alert("person1: " + person1.colors);    // red, blue, green, yellow
 7     alert("person2: " + person2.colors);    // red, blue, green
 8 
 9     person1.sayName();    // Gee
10     person2.sayAge();    // 21
11 };
12 
13 function object(o){
14     function F() {}
15     F.prototype = o;
16     return new F();
17 }
18 
19 /**
20  * 继承超类型的方法
21  * @param  {Object} subType   子类型
22  * @param  {Object} superType 超类型
23  * @return {null}
24  */
25 function inheritPrototype(subType, superType) {
26     var prototype = object(superType.prototype);    // 创建对象
27     prototype.constructor = subType;    // 增强对象
28     subType.prototype = prototype;    // 指定对象
29 }
30 
31 function SuperType(name) {
32     this.name = name;
33     this.colors = ["red", "blue", "green"];
34 }
35 
36 SuperType.prototype.sayName = function() {
37     alert(this.name);
38 };
39 
40 function SubType(name, age) {
41     SuperType.call(this, name);    // 继承属性,并传递参数,子类型将具有独立属性而非共享属性
42 
43     this.age = age;
44 }
45 
46 inheritPrototype(SubType, SuperType);
47 
48 SubType.prototype.sayAge = function () {
49     alert(this.age);
50 };
复制代码

 

posted @   就只是小茗  阅读(217)  评论(0编辑  收藏  举报
编辑推荐:
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
· 对象命名为何需要避免'-er'和'-or'后缀
阅读排行:
· “你见过凌晨四点的洛杉矶吗?”--《我们为什么要睡觉》
· 编程神器Trae:当我用上后,才知道自己的创造力被低估了多少
· C# 从零开始使用Layui.Wpf库开发WPF客户端
· C#/.NET/.NET Core技术前沿周刊 | 第 31 期(2025年3.17-3.23)
· 开发的设计和重构,为开发效率服务
点击右上角即可分享
微信分享提示