Is there a way I can do all of this in a constructor?
obj = new Object();
obj.city = "A";
obj.town = "B";
Is there a way I can do all of this in a constructor?
obj = new Object();
obj.city = "A";
obj.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);
This would be the prototype way, which i prefere over plain object literals when i need more then one instance of the object.
function cat(name) {
this.name = name;
this.talk = function() {
alert( this.name + " say meeow!" )
}
}
cat1 = new cat("felix")
cat1.talk() //alerts "felix says meeow!"
try this:
function MyObject(city, town) {
this.city = city;
this.town = town;
}
MyObject.prototype.print = function() {
alert(city + " " + town);
}
obj = new MyObject("myCity", "myTown");
obj.print();
Do not complicate things. Here is a simplest way of defining a constructor.
var Cont = function(city, town) {
this.city = city;
this.town = town;
}
var Obj = new Cont('A', 'B');