javascript中继承的3种方式

叁歲伎倆 2022-05-28 03:35 325阅读 0赞
  1. function S() {
  2. this.name = "sss";
  3. }
  4. S.prototype.say = function() {
  5. console.log(this.name);
  6. }
  7. //ES6
  8. class A extends S {
  9. constructor(){
  10. super();
  11. }
  12. }
  13. //寄生组合继承
  14. function B() {
  15. S.call(this);
  16. }
  17. B.prototype = Object.create(S.prototype)
  18. B.prototype.constructor = B;
  19. //组合继承(构造函数+原型),原型中会多父构造函数中的属性
  20. function C() {
  21. S.call(this);
  22. }
  23. C.prototype = new S();
  24. C.prototype.constructor = C;
  25. var a = new A();
  26. a.say();
  27. console.log(a instanceof A);
  28. console.log(a instanceof S);
  29. console.log(A.prototype.isPrototypeOf(a));
  30. console.log(S.prototype.isPrototypeOf(a));
  31. var b = new B();
  32. b.say();
  33. console.log(b instanceof B);
  34. console.log(b instanceof S);
  35. console.log(B.prototype.isPrototypeOf(b));
  36. console.log(S.prototype.isPrototypeOf(b));
  37. var c = new C();
  38. c.say();
  39. console.log(c instanceof C);
  40. console.log(c instanceof S);
  41. console.log(C.prototype.isPrototypeOf(c));
  42. console.log(S.prototype.isPrototypeOf(c));

发表评论

表情:
评论列表 (有 0 条评论,325人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Javascript继承方式

    一、原型链 ECMAScript中的继承方式主要通过原型链实现。 原型链的基本构想:每个构造函数都有一个原型对象,原型有一个属性指回构造函数本身,实例有一个内部指针指