2016-06-28 10 views
0

明確化とObject.createパターン

<html> 
 
    <head> 
 
     <meta charset="UTF-8"> 
 
     <title>Animal</title> 
 
     <script type="text/javascript" > 
 

 
      var Animal = function() { 
 
       return { 
 
        sayName: function (name) { 
 
         alert("My name is " + name); 
 
        } 
 
       } 
 
      } 
 
      // Animal object 
 
      var animalObj = new Animal(); 
 
      // Cat1 inherits from animalObj using prototype pattern. 
 
      var Cat1 = function() { 
 
       var obj = { 
 
        run: function() { 
 
         alert("I am running..."); 
 
        }, 
 
       }; 
 
       obj.prototype = animalObj; 
 
       return obj; 
 

 
      } 
 

 
      // Cat1 inherits from animalObj using Object.create pattern. 
 
      var Cat2 = function() { 
 
       var obj = Object.create(animalObj); 
 
       obj.run = function() { 
 
        alert("I am running..."); 
 
       }; 
 
       return obj; 
 

 
      } 
 
      var cat1 = new Cat1(); 
 
      cat1.prototype.sayName("Cat1"); 
 
      cat1.run(); 
 

 
      var cat2 = new Cat2(); 
 
      cat2.sayName("Cat2"); 
 
      cat2.run(); 
 

 
     </script> 
 
    </head> 
 
    <body> 
 
    </body> 
 
</html>

私はAnimalクラスを持っています。それはsayNameメソッドを持っています。

Cat1はPrototypeパターンを使用してAnimalから継承します。

Cat2はObject.createパターンを使用して動物から継承しています。

cat1の場合、cat1.prototype.sayName("Cat1");の代わりにcat1.sayName("Cat1")のようなsayNameを呼び出すことはできますか? CAT2の場合

、それはCat2の独自のプロパティと関数を定義してから、私はきれいな構造を持つことができるように

var Cat2 = function() { 
     var obj = { 
      run: function() { 
       alert("I am running..."); 
      }, 
     }; 

     // Here I want obj inherits Animal. How can I do that? 
     return obj; 
} 

のような動物を継承することが可能です。私は明確にしてください

obj.run = function() { 
    alert("I am running..."); 
}; 

のように使用する必要はありません。

+0

呼び出すことができますラインに置き換えますプロトタイプ継承 – ftor

+0

'Object.create'は多重継承をサポートしていません。しかし、あなたは[連結](http://stackoverflow.com/questions/2800964/benefits-of-prototypal-inheritance-over-classical)でいくつかのプロトタイプを継承することができます – ftor

+0

cat1.prototypeは通常のプロパティとして扱われますか?だから私はCat1でAnimalを継承できますか? –

答えて

-1

obj.prototype = animalObj; 

Object.setPrototypeOf(obj, animalObj); 

そして、あなたはこれではないので、あなたは、とても奇妙な `cat1.prototype.sayName`を呼び出す必要があり

cat1.sayName("Cat1");