技术头条 - 一个快速在微博传播文章的方式     搜索本站
您现在的位置首页 --> JavaScript --> javascript继承机制

javascript继承机制

浏览:1040次  出处信息

   1、构造函数继承

1

   2

   3

   4

   5

   6

   7

   8

   9

   10

   11

   12

   13

   

function Animal(){

       this.species = "动物";

   }

   

   function Cat(name, color){

       Animal.apply(this, arguments);

       this.name = name;

       this.color = color;

   }

   

   var cat1 = new Cat("大毛", "黄色");

   

   console.log(cat1.species);  // 动物

   1.1、call与apply的区别

1

   2

   3

   4

   5

   6

   7

   8

   9

   10

   11

   12

   13

   14

   15

   

function Animal(name){

       this.name = name;

       this.showName = function(){

           console.log(this.name);

       }

   }

   

   function Cat(name){

       Animal.call(this, name); // class.call(obj, argument1, argument2, ...)

       // Animal.apply(this, arguments); // class.apply(obj, arguments)

   }

   

   var cat = new Cat("黑猫警长");

   

   cat.showName();

   2、原型继承

1

   2

   3

   4

   5

   6

   7

   8

   9

   10

   11

   12

   13

   

function Animal(){

       this.species = "动物";

   }

   

   function Cat(name, color){

       this.name = name;

       this.color = color;

   }

   

   Cat.prototype = new Animal();

   

   var cat1 = new Cat("大毛", "黄色");

   console.log(cat1.species); // 动物

   2.1 构造函数中使用原型继承需要用类(函数)名,不能用this

   function Cat(name, color){

    this.prototype = new Animal(); // 无效

     Cat.prototype = new Animal(); // 有效

    this.name = name;

    this.color = color;

   }

   2.2 apply不能继承原型属性/方法

1

   2

   3

   4

   5

   6

   7

   8

   9

   10

   11

   12

   13

   14

   15

   

function Animal(name){

       this.name = name;

   }

   

   // Animal.apply(this, arguments); 不能继承该方法

   Animal.prototype.showName = function(){

       console.log(this.name);

   }

   

   function Cat(name){

       Animal.apply(this, arguments);

   }

   

   var cat = new Cat("黑猫警长");

   cat.showName(); // TypeError: Object #<Cat> has no method 'showName'

   总结:如果使用class.apply/call继承,只在constructor中实现父类的属性和方法,不使用prototype;如果使用class.prototype = new parent_class()继承,则可以使用prototype定义属性和方法。

建议继续学习:

  1. 在C++里写一个不能被继承的类    (阅读:5682)
  2. PHP面向对象编程的三大特性    (阅读:3133)
  3. 多重继承及虚继承中对象内存的分布    (阅读:3059)
  4. Linux 系统文件描述符继承带来的危害    (阅读:2666)
  5. 关于python和C++中子类继承父类数据的问题    (阅读:2606)
  6. C++ 中的接口继承与实现继承    (阅读:2510)
  7. Javascript继承机制的设计思想    (阅读:2457)
  8. JavaScript 函数、作用域和继承    (阅读:2103)
  9. 再论Javascript的类继承    (阅读:2074)
  10. Javascript面向对象编程(二):继承    (阅读:1926)
QQ技术交流群:445447336,欢迎加入!
扫一扫订阅我的微信号:IT技术博客大学习
© 2009 - 2024 by blogread.cn 微博:@IT技术博客大学习

京ICP备15002552号-1