1

Lately, on a number of js game making blogs and sites etc. I have seen a new convention for creating some kind of "instance". It looks like this:

var newCharacter = function (x, y) {
    return {
        x: x,
        y: y,

        width: 50,
        height: 50,

        update: function () {
            //do update stuff here
        }
    };
};

var myCharacter = newCharacter(20, 30); //create "instance"

As opposed to the the traditional way:

 var Character = function (x, y) {
    this.x = x;
    this.y = y;

    this.width = 50;
    this.height = 50;

    this.update = function () {
        //do update stuff here
    };
};

var myCharacter = new Character(20, 30); //create intance

I was curious what the advantage of using the first way might be. Is it more efficent, semantic, or faster?

Matt
  • 666
  • 1
  • 6
  • 11
  • Well if I am not wrong the 'new' in the second section allocate space on the heap for the instance, as oppose to the first section where no other space is allocate so I am wondering if the first should just be use for static class or single instance class? Dont take this for granted I am also asking myself what the difference between to 2 section are – Sebastien Jun 20 '14 at 18:32
  • 2
    These are both about the same or the difference is very minimal in terms of speed, the traditional way is more common as is closer to other languages, hence I recommend that. If you want to be more efficient you can also use **prototypes**. I don't recommend the first way, the `new` operator is there for a reason. You may have inheritance problems the first way. – Spencer Wieczorek Jun 20 '14 at 18:42
  • 2
    Do you have a moment to talk about prototypal inheritance? :P Like Spencer says, I highly recommend to use prototypal inheritance. This way, each instance only have the attributes on it and a reference to the methods on the prototype that means less memory usage. You can read about it here: http://stackoverflow.com/questions/2800964/benefits-of-prototypal-inheritance-over-classical – neiker Jun 20 '14 at 19:13

0 Answers0