IT技术博客大学习 共学习 共进步

javascript继承机制

流水孟春 2013-08-13 13:04:31 浏览 1,722 次

   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++里写一个不能被继承的类 (阅读 6,483)
  2. PHP面向对象编程的三大特性 (阅读 4,543)
  3. 多重继承及虚继承中对象内存的分布 (阅读 4,062)
  4. Linux 系统文件描述符继承带来的危害 (阅读 3,583)
  5. 关于python和C++中子类继承父类数据的问题 (阅读 3,445)
  6. C++ 中的接口继承与实现继承 (阅读 3,401)
  7. JavaScript 函数、作用域和继承 (阅读 3,285)
  8. Javascript继承机制的设计思想 (阅读 3,262)
  9. 再论Javascript的类继承 (阅读 3,004)
  10. Javascript继承-原型的陷阱 (阅读 2,961)