2017-01-02 117 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

这在第一个例子中引用了窗口对象,因为我认为这个对象正在制作中。第二个是引用一个尚未创建的对象,所以它不起作用 –

回答

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"); 

这样你会得到你想要的结果。