寄生组合式继承

 1 //寄生组合式继承

 2 function object(o) {

 3     function F() {}

 4     F.prototype = o;

 5     return new F();

 6 }

 7 

 8 function inheritPrototype(subType, superType) {

 9     var prototype = object(superType.prototype);

10     prototype.constructor = subType;

11     subType.prototype = prototype;

12 }

13 

14 function SuperType(name) {

15     this.name = name;

16     this.colors = ["red", "blue", "green"];

17 }

18 

19 SuperType.prototype.sayName = function() {

20     console.log(this.name);

21 };

22 

23 function SubType(name, age) {

24     SuperType.call(this, name);

25     this.age = age;

26 }

27 

28 inheritPrototype(SubType, SuperType);

29 

30 SubType.prototype.sayAge = function() {

31     console.log(this.age);

32 };

33 

34 var instance1 = new SubType("Nicholas", 29);

35 instance1.colors.push("black");

36 console.log(instance1.colors);

37 instance1.sayName();

38 instance1.sayAge();

39 

40 var instance2 = new SubType("Greg", 27);

41 console.log(instance2.colors);

42 instance2.sayName();

43 instance2.sayAge();

你可能感兴趣的:(继承)