2017-01-02 3 views
-1

私はオブジェクト内にたくさんのオブジェクトを作成する作業をしていました。たとえば、オブジェクトのプロパティとしてコンストラクタを配置して、すべてを少しカプセル化することをお勧めします。コンストラクタ関数?

//surprisingly you can't do this it returns an error 
// Uncaught TypeError: this.Dogs is not a constructor 
let dogs={ 
     keagon: new this.Dog("keagon","shih sue"), 
     spike: new this.Dog("spike","lab"), 
     Dog: function(name,breed){ 
     this.name=name; 
     this.breed=breed;  
    } 
} 

//nor can you do this 

let dogs2={ 
     keagon: new dogs2.Dog("keagon","shih sue"), 
     spike: new dogs2.Dog("spike","lab"), 
     Dog: function(name,breed){ 
     this.name=name; 
     this.breed=breed;  
    } 
} 
// this again returns an error 
//Uncaught ReferenceError: dogs2 is not defined 
//this leads me to believe you cant access objects within themselves  
//without the this key word correct? If so, I find a that a bit surprising 
//because you can call functions within themselves. 

//I was able to encapsulate like I wanted, by storing the newly created 
//objects as properties of their constructor, for example 

function Dog(name,breed){ 
     this.name=name; 
     this.breed=breed; 
} 
Dog.dogs={ 
      keagon: new Dog("keagon","shih sue"), 
      spike: new Dog("spike","lab") 
     } 
    // Dog.dogs.keagon > outputs Dog {name: "keagon", breed: "shih sue"} 
    //keagon object is a object type of object and not of function so it also 
    //inherits all the Object methods 

ですから、オブジェクトのコンストラクタを置くことができない理由があるない場合プットコンストラクタとオブジェクトのプロパティを配置する方法がありますが、あなたは自分のコンストラクタでオブジェクトを格納することができますし、この悪い考えをしているのですか?オブジェクトを作成し、それらをコンストラクタに格納してカプセル化すると悪い習慣になるでしょうか?私が気付いていない問題が起こっていますか?

+0

これは最初の例ではオブジェクトが作成されていると思われるため、ウィンドウオブジェクトを参照していると思います。 2つ目はまだ作成されていないオブジェクトを参照しているため、動作しません –

答えて

0

私はあなたが変数を宣言することはできないと思うし、彼自身の建設にそれを使用します。 あなたは、あなたが望んでいた結果を得るでしょう。この

let dogs2={ 
     Dog: function(name,breed){ 
     this.name=name; 
     this.breed=breed;  
    } 
} 

そして

dogs2.keagon= new dogs2.Dog("keagon","shih sue"); 
dogs2.spike= new dogs2.Dog("spike","lab"); 

この方法のように行うことができます。

関連する問題