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

javascript继承机制

流水孟春 2013-08-13 13:04:31 累计浏览 1,742 次
本机暂存

   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. JQuery实现Excel表格呈现 (累计阅读 48,262)
  2. 深入理解Javascript之执行上下文(Execution Context) (累计阅读 18,263)
  3. 从输入 URL 到页面加载完成的过程中都发生了什么事情? (累计阅读 15,801)
  4. 图片动态局部毛玻璃模糊效果的实现 (累计阅读 14,761)
  5. 天朝第二代身份证号码的验证机制 (累计阅读 14,681)
  6. HTML 5 的data-* 自定义属性 (累计阅读 14,241)
  7. 分享一个JQUERY颜色选择插件 (累计阅读 14,140)
  8. 什么是全栈工程师? (累计阅读 13,941)
  9. 快速排序(Quicksort)的Javascript实现 (累计阅读 11,641)
  10. 7 天打造前端性能监控系统 (累计阅读 11,100)