2012-08-02 11 views
5

C'è un modo per eseguire tutto questo in un costruttore?Istanziare un oggetto javascript e popolare le sue proprietà in una singola riga

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

Sì, certo. Potete vedere alcuni utilizzo qui: [domanda precedenza risposto] [1] [1]: http://stackoverflow.com/questions/1114024/constructors-in-javascript-objects – Steve

+0

possibile duplicato del [Crea un oggetto con proprietà,] (http://stackoverflow.com/questions/8224680/create-an-object-with-properties) –

+0

http://www.phpied.com/3-ways-to-define-a- javascript-class/ – Kasper

risposta

13

Perché non basta fare in questo modo:

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

e le virgolette in giro per città e città sono facoltative. – Thilo

+0

Proprio così, Thilo, ho passato troppo tempo con "JSON" ;-) – nez

5

Come così:

var obj = { 
    city: "a", 
    town: "b" 
} 
2

provare questo

var obj = { 
    city : "A", 
    town : "B" 
}; 
1
function cat(name) { 
    this.name = name; 
    this.talk = function() { 
     alert(this.name + " say meeow!") 
    } 
} 

cat1 = new cat("felix") 
cat1.talk() //alerts "felix says meeow!" 
5
function MyObject(params) { 
    // Your constructor 
    this.init(params); 
} 

MyObject.prototype = { 
    init: function(params) { 
     // Your code called by constructor 
    } 
} 

var objectInstance = new MyObject(params); 

Questo sarebbe il modo prototipo, che preferisco sui normali oggetti letterali quando ho bisogno di più di una istanza dell'oggetto.

0

provare questo:

function MyObject(city, town) { 
    this.city = city; 
    this.town = town; 
} 

MyObject.prototype.print = function() { 
    alert(city + " " + town); 
} 

obj = new MyObject("myCity", "myTown"); 
obj.print(); 
0

Non complicare le cose. Ecco un modo più semplice per definire un costruttore.

var Cont = function(city, town) { 
      this.city = city; 
      this.town = town; 
      } 

var Obj = new Cont('A', 'B'); 
+0

Questo avrebbe portato a metodi solo privati ​​nella tua classe. Utilizzando il prototipo, puoi definire metodi accessibili dall'esterno della tua classe. Se hai bisogno di metodi privati, puoi ancora definirli all'interno della funzione di costruzione. – Sutuma

+0

Questo non porterà a metodi privati. Per favore leggi http://javascript.crockford.com/private.html –

+0

Dal tuo link: "I metodi privati ​​sono le funzioni interne del costruttore." Questo è fondamentalmente ciò che avresti alla fine, se dichiarassi le funzioni nella tua definizione. – Sutuma

1

scrivi tu costruttore personalizzato:

function myObject(c,t) { 
    this.city = c; 
    this.town = t; 
} 

var obj = new myObject("A","B"); 
Problemi correlati