8

Possible Duplicate:
How to “properly” create a custom object in JavaScript?

Sorry if this has been answered before but I'm a bit overwhelmed by the amount of choices offered to be in regard to creating custom objects in Javascript. I'm not sure of their respective strengths or weaknesses or whether or not they differ at all.

Here are some of the different ways I have found to construct objects:

1: New Object

person = new Object()
person.name = "Tim Scarfe"
person.height = "6Ft"

person.run = function() {
    this.state = "running"
    this.speed = "4ms^-1"
}

2: Literal Notation

timObject = {
    property1 : "Hello",
    property2 : "MmmMMm",
    property3 : ["mmm", 2, 3, 6, "kkk"],
    method1 : function(){alert("Method had been called" + this.property1)}
};

3: Functions

function AdBox() {
    this.width = 200;
    this.height = 60;
    this.text = 'default ad text';
    this.prototype.move = function() {
        // code for move method goes here
    }
}
this.prototype.display = function() {
    // code
}

I even saw some more ways but they seemed less common.. As you can see I'm not exactly sure what the standard is when someone just wants a simple object with fields and methods.

Thanks for reading.

Community
  • 1
  • 1
Ryan Peschel
  • 11,087
  • 19
  • 74
  • 136
  • 1
    in your `AdBox` function, it should be `this.move = function` not `this.prototype.move = function`. – zzzzBov Jun 10 '12 at 23:21
  • @zzzzBov: Yeah I just copied and pasted from [here](http://javascript.about.com/library/bltut35.htm). They said it could be done either way but there are differences. – Ryan Peschel Jun 10 '12 at 23:22
  • 2
    http://stackoverflow.com/questions/1595611/how-to-properly-create-a-custom-object-in-javascript#1598077 – zerkms Jun 10 '12 at 23:23
  • As a side note, `about.com` tends not to have very good information about programming languages. – zzzzBov Jun 10 '12 at 23:25
  • Why was this question closed? It is similar but not identical to the referenced question. – chuckj Jun 10 '12 at 23:45

1 Answers1

0

The first and second options are functionally identical. Most developers choose to use the literal notation because it's a little shorter.

The third option is generally only used when you're looking to create reusable objects (i.e. inheritance). In this case, the function acts as a "constructor" - which is a function that returns a new object instance that can inherit methods and properties defined in the constructor's prototype.

Kevin Ennis
  • 14,226
  • 2
  • 43
  • 44
  • Which part says it's "good practice" not to use the `new` keyword? I'd have to disagree with that advice. – Kevin Ennis Jun 11 '12 at 00:23
  • Shoot you're right wrong link. I'll update this after I find the correct link (which was just not use to *new object()*). Sorry I misstated that in my original (deleted) comment). – Erik Philips Jun 11 '12 at 00:37