7

Is there a way I can do all of this in a constructor?

  obj = new Object();
  obj.city = "A";
  obj.town = "B";
John
  • 1
  • 13
  • 98
  • 177
Alan2
  • 23,493
  • 79
  • 256
  • 450
  • Yes, of course. You can see some usage here: [Previously answered question][1] [1]: http://stackoverflow.com/questions/1114024/constructors-in-javascript-objects – Steve Aug 02 '12 at 12:32
  • possible duplicate of [Create an object with properties,](http://stackoverflow.com/questions/8224680/create-an-object-with-properties) – Felix Kling Aug 02 '12 at 12:34
  • http://www.phpied.com/3-ways-to-define-a-javascript-class/ – Kasper Aug 02 '12 at 12:25

8 Answers8

16

Why don't you just do it this way:

var obj = {"city": "A", "town": "B"};
nez
  • 256
  • 2
  • 6
5

Like so:

var obj = {
    city: "a",
    town: "b"
}
Austin
  • 6,026
  • 2
  • 24
  • 24
5
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.

stlvc
  • 833
  • 5
  • 16
2

try this

var obj = {
    city : "A",
    town : "B"
};
Shades88
  • 7,934
  • 22
  • 88
  • 130
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!"
RubbleFord
  • 7,456
  • 9
  • 50
  • 80
1

You can write your custom constructor :

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

var obj = new myObject("A","B");
DaveShaw
  • 52,123
  • 16
  • 112
  • 141
Skandh
  • 426
  • 3
  • 18
0

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();
Vodun
  • 1,377
  • 1
  • 10
  • 12
0

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');
  • This would lead to private only methods in your class. By using prototype, you can define methods which are accessible from outside of your class. If you need private methods, you can still define them within the constructor function. – stlvc Aug 02 '12 at 12:56
  • This will not lead to private methods. Please read http://javascript.crockford.com/private.html –  Aug 02 '12 at 13:03
  • From your link: "Private methods are inner functions of the constructor." This is basically what you would end up with, if you would declare functions in your definition. – stlvc Aug 02 '12 at 14:11