Javascript原型继承类

克罗蒂悖论
      <html>
      <body>
      <script>    
      function animal(kane){
      this.kane:"aaaaa";
      }
      function Rabbit(name) {
      this.name = name;
      } 
      Rabbit.prototype.__proto__=animal.prototype;
      var a=new animal("aaaa");// this wont work when i put a alert box
      var rabbit = new Rabbit('John');
      alert( rabbit.kane );// i should get aaaa but i am getting undefined
     </script>
     </body>
     </html>

我应该在警报框中得到aaaa,但是在这种情况下我该如何进行原型继承?何时使用animal.prototype以及何时使用新的animal()

拉曼夫
  kane:"aaaaa";

这里的语法不正确,应该是 this.kane = "aaaaa";

现在,对于Rabbit实例来获取属性kane,您可以使用构造函数窃取,例如

 function Rabbit(name) {
     animal.call(this); // constructor stealing
      this.name = name;
 } 

另一种方法是

var a=new animal("aaaa");
var rabbit  = Object.create(a);

在这种方法中,不需要构造函数窃取,因为您直接从的实例继承 animal

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章