Instanciation d'un objet javascript et remplissage de ses propriétés en une seule ligne

Est-ce que je peux faire tout cela dans un constructeur?

obj = new Object(); obj.city = "A"; obj.town = "B"; 

Pourquoi ne le faites-vous pas de cette façon?

 var obj = {"city": "A", "town": "B"}; 

Ainsi:

 var obj = { city: "a", town: "b" } 
 function MyObject(params) { // Your constructor this.init(params); } MyObject.prototype = { init: function(params) { // Your code called by constructor } } var objectInstance = new MyObject(params); 

Ce serait la manière prototype, que je préfère sur les littéraux d'objets simples lorsque j'ai besoin de plus d'une instance de l'objet.

essaye ça

 var obj = { city : "A", town : "B" }; 
 function cat(name) { this.name = name; this.talk = function() { alert( this.name + " say meeow!" ) } } cat1 = new cat("felix") cat1.talk() //alerts "felix says meeow!" 

Vous pouvez écrire votre constructeur personnalisé:

 function myObject(c,t) { this.city = c; this.town = t; } var obj = new myObject("A","B"); 

essaye ça:

 function MyObject(city, town) { this.city = city; this.town = town; } MyObject.prototype.print = function() { alert(city + " " + town); } obj = new MyObject("myCity", "myTown"); obj.print(); 

Ne compliquez pas les choses. Voici la façon la plus simple de définir un constructeur.

 var Cont = function(city, town) { this.city = city; this.town = town; } var Obj = new Cont('A', 'B');