对象内部的构造函数?

时间:2017-01-02 12:00:39

标签: javascript constructor encapsulation

我正在创建一个对象中的一堆对象,我认为将构造函数作为一个对象属性来封装所有东西是个好主意。例如。

//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

那么有没有办法放置构造函数和对象属性,如果没有这个原因你不能将构造函数放在对象中,但是你可以在它们的构造函数上存储对象并且这样做是个坏主意吗?创建对象并将它们存储在构造函数中以封装它们是不好的做法?是否有任何我不知道的问题?

1 个答案:

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

这样你就可以得到你想要的结果。

相关问题