2017-06-24 1 views
-1

animalを継承するcatがあります。JavaScriptの基本型が `instanceof`派生型のコンストラクタです

私はcatがそのコンストラクタのインスタンスであり、animalのコンストラクタであると考えています。

animalは、catコンストラクタのインスタンスです。

var animal = {}; 
 

 
var cat = Object.create(animal); 
 

 
console.log('cat instanceof animal.constructor: ' + (cat instanceof animal.constructor)); 
 
console.log(' cat instanceof cat.constructor: ' + (cat instanceof cat.constructor)); 
 
console.log('animal instanceof cat.constructor: ' + (animal instanceof cat.constructor));

なぜanimalcatのインスタンスでありますか?

+0

は 'にconsole.log(cat.constructor、cat.constructor === animal.constructor)試してみてください;' – 4castle

+0

4castle @おかげで、彼らは等しく_why_ですか?派生型と基底型が同じコンストラクタを持つ方法を理解できません。 – BanksySan

+0

'cat'は' constructor'プロパティが実際には定義されていないので、 'cat.constructor'にアクセスしようとするとプロトタイプオブジェクトの' constructor'値が使われます。 – 4castle

答えて

0

以下のコードでは、この概念を理解できるかもしれません。全体鎖

  • Object.prototype.constructorをチェック:instanceoftypeofconstructor

    • instanceof差があり

    • typeofをインスタンス・オブジェクトを作成したオブジェクトのコンストラクタ関数への参照を返します。考えられるもののデータ型を返す
    今、あなたのケースでは10

    :チェックコメント

    var animal = {}; //animal is an object 
    //animal.constructor is a parent Object constructor function 
    
    var cat = Object.create(animal); 
    //cat is an object created using animal object 
    //cat.constructor will also return parent Object constructor because. 
    //To remember this just remember that right side of instanceof always needs to be callable (that is, it needs to be a function) 
    
    console.log('cat instanceof animal.constructor: ' + (cat instanceof animal.constructor)); 
    //this will return true as animal.constructor is nothing but parent Object constructor function and every object is instanceof that parent Object() 
    
    console.log(' cat instanceof cat.constructor: ' + (cat instanceof cat.constructor)); 
    //this will also return true for the same reason as mentioned above 
    
    console.log('animal instanceof cat.constructor: ' + (animal instanceof cat.constructor)); 
    //this also has the same reason 
    
  • +0

    この行は正しいですか? "' constructor':そのオブジェクトを構築したものだけを返します。 "これは 'cat'コンストラクタが' Object'コンストラクタであるため、そうではないようです。 – BanksySan

    +0

    私はそれをよく言い換えるべきです@BanksySan –

    関連する問題