-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
那么,有没有,如果有,你不能把构造函数中的对象的理由把放构造函数和对象属性的一种方式,但你可以存储在它们的构造函数的对象和正在做这一个坏主意?创建对象并将它们存储在它们的构造函数中封装它们会是不好的做法吗?是否有任何我不知道的问题?
这在第一个例子中引用了窗口对象,因为我认为这个对象正在制作中。第二个是引用一个尚未创建的对象,所以它不起作用 –