several way to implement inheritance in javascript

 1 //1.prototype chain inheritance
 2     function SuperType() {
 3         this.property = true;
 4     }
 5     SuperType.prototype.getSuperValue = function () {
 6         return this.property;
 7     };
 8     function SubType() {
 9         this.subproperty = false;
10     }
11 
12     //inherited from SuperType
13     SubType.prototype = new SuperType();
14     SubType.prototype.getSubValue = function () {
15         return this.subproperty;
16     };
17 
18     //2.constructor stealing inheritance
19     function SuperType() {
20         this.colors = ["red","blue","green"];
21     }
22     function SubType() {
23         //inherited from SuperType
24         SuperType.call(this);
25     }
26 
27     //3.combination inheritance
28     function SuperType(name) {
29         this.name = name;
30         this.colors = ["red", "blue", "green"];
31     }
32     SuperType.prototype.sayName = function () { alert(this.name); };
33     function SubType(name,age) {
34         //inherit properties
35         SuperType.call(this, name); //second call superType()
36         this.age = age;
37     }
38     //inherit method
39     SubType.prototype = new SuperType(); //first call superType()
40     SubType.prototype.sayAge = function () { alert(this.age); };
41 
42     //4.prototypal inheritance in javascript
43     function object(o) {
44         function F() { }
45         F.prototype = o;
46         return new F();
47     }
48 
49     //5.parasitic inheritance
50     function createAnother(original) {
51         var clone = object(original);
52         clone.sayHi = function () { alert("hi"); };
53         return clone;
54     }
55 
56     //6.parasitic combinate inheritance
57     function inheritPrototype(subType, superType) {
58         var prototype = object(superType.prototype);
59         prototype.constructor = subType;
60         subType.prototype = prototype;
61     }
62     function SuperType(name) {
63         this.name = name;
64         this.colors = ["red","blue","green"];
65     }
66     SuperType.prototype.sayName = function () { alert(this.name); };
67 
68     function SubType(name, age) {
69         SuperType.call(this, name);
70         this.age = age;
71     }
72     inheritPrototype(SubType,SuperType);
73     SubType.prototype.sayAge = function () { alert(this.age); };

 

转载于:https://www.cnblogs.com/ongoing/archive/2013/05/14/3078987.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值