首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >理想的继承范式——寄生组合式继承

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

作者头像
就只是小茗
发布2018-12-12 18:01:42
4890
发布2018-12-12 18:01:42
举报
 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 };
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-11-12 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档