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";
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";
Come così:
var obj = {
city: "a",
town: "b"
}
provare questo
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!"
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.
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();
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');
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
Questo non porterà a metodi privati. Per favore leggi http://javascript.crockford.com/private.html –
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
scrivi tu costruttore personalizzato:
function myObject(c,t) {
this.city = c;
this.town = t;
}
var obj = new myObject("A","B");
Sì, certo. Potete vedere alcuni utilizzo qui: [domanda precedenza risposto] [1] [1]: http://stackoverflow.com/questions/1114024/constructors-in-javascript-objects – Steve
possibile duplicato del [Crea un oggetto con proprietà,] (http://stackoverflow.com/questions/8224680/create-an-object-with-properties) –
http://www.phpied.com/3-ways-to-define-a- javascript-class/ – Kasper