Search code examples
javascriptprototypeprototype-programming

Javascript prototype inheritance classes


      <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>

i should get aaaa in the alert box but how can i do a prototypical inheritance in this situation WHEN TO USE animal.prototype and when to use new animal()


Solution

  •   kane:"aaaaa";
    

    incorrect syntax here , it should be this.kane = "aaaaa";

    now for Rabbit instances to get the property kane,you can use constructor stealing like

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

    Another approach would be

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

    in this approach constructor stealing is not required since your directly inheriting from an instance of animal