2016-05-28 139 views
0

我正在研究JavaScript继承,第一次,我似乎无法得到它的工作,或者我没有正确理解它。 所以我有一些代码在这里,让我们来看看它:如何实现JavaScript继承

<script language="javascript" type="text/javascript">    
      //object and prototype 
      function cat(name){//object constructor 
       this.name = name;//property 
       this.talk = function(){//method 
        console.log(this.name + " say meeow"); 
       } 
      }   
      cat1 = new cat("Cat 1 Felix") 
      cat1.talk();    
      cat2 = new cat("cat 2 Joy") 
      cat2.talk() 
      //inheritance 
      function isleManCat(name){ 
       cat.call(this,name) 
       this.feature = "no tail" 
       this.detail = function(){ 
        console.log(this.name + " has " + this.feature); 
       } 
      } 
      isleManCat.prototype = new cat(); 
      cat3 = new isleManCat("isle of Man cat") 
      cat3.talk(); 
      cat3.detail();   
     </script> 

所以我有2只猫对象这里CAT1和CAT2打印预期的结果:

Cat 1 Felix say meeow 
cat 2 Joy say meeow 

。然后CAT3是应该从猫()继承isleOfMan()的猫,我本来以为它会继承来自猫的name属性(),但它打印未定义:

undefined say meeow 
undefined has no tail 

有人可以请让我知道为什么它不工作,我做错了,请不要理解,因为我似乎不明白? 感谢

+1

你期待什么名字的猫具有? – Amit

+1

你从未为你的'isleManCat'指定一个名字。 – RainingChain

+1

'isleManCat()'需要调用它继承的构造函数。有数以千计的关于Javascript的继承教程和关于同一主题的数百个答案。请在您遇到困难时阅读并提出更具体的问题。如果你还没有做过自己的研究,那么我们不是一个通用的教程服务。例如,从[这里]开始(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain)。 – jfriend00

回答

1

你的第三个小猫获得cat不会产生你预期的结果,因为cat构造不会因isleManCat的构造函数自动奇迹般地被称为!而你的第三只小猫根本没有名字!

 // You need to pass the name of the whole cat to this constructor 
     // to later give it as argument to base constructor (i.e. cat()) 
     function isleManCat(name){ 
      // This is calling cat constructor function setting the "this" 
      // keyword to the "this" of isleManCat 
      cat.call(this, name); 

      this.feature = "no tail" 
      this.detail = function(){ 
       console.log(this.name + " has " + this.feature); 
      } 
     } 

在ECMA脚本5.x的,你也可以使用Function.prototype.applyarguments保留关键字传递isleOfMan构造函数的参数与数组cat

 function isleManCat(){ 
      cat.apply(this, arguments); 

      this.feature = "no tail" 
      this.detail = function(){ 
       console.log(this.name + " has " + this.feature); 
      } 
     } 

而且,在ECMA脚本2015年及以上,你可以使用其余参数

 function isleManCat(...args){ 
      // This is calling cat constructor function setting the "this" 
      // keyword to the "this" of isleManCat 
      cat.apply(this, args); 

      this.feature = "no tail" 
      this.detail = function(){ 
       console.log(this.name + " has " + this.feature); 
      } 
     }