Instantiating A Javascript Object And Populating Its Properties In A Single Line
Is there a way I can do all of this in a constructor? obj = new Object(); obj.city = 'A'; obj.town = 'B';
Solution 1:
Why don't you just do it this way:
var obj = {"city": "A", "town": "B"};
Solution 2:
Like so:
var obj = {
city: "a",
town: "b"
}
Solution 3:
function MyObject(params) {
// Your constructor
this.init(params);
}
MyObject.prototype = {
init: function(params) {
// Your code called by constructor
}
}
var objectInstance = new MyObject(params);
This would be the prototype way, which i prefere over plain object literals when i need more then one instance of the object.
Solution 4:
try this
var obj = {
city : "A",
town : "B"
};
Solution 5:
function cat(name) {
this.name = name;
this.talk = function() {
alert( this.name + " say meeow!" )
}
}
cat1 = new cat("felix")
cat1.talk() //alerts "felix says meeow!"
Post a Comment for "Instantiating A Javascript Object And Populating Its Properties In A Single Line"