Oliver Watkins
Oliver Watkins

Reputation: 13499

Names for different Javascript Object Notation

Is there a name for describing the different ways you can define an object in Javascript?

There is this method which is more 'class-like' :

function MyObject() {

    this.aMethod= new function(){
    };

    this.anotherMethod = new function(){
    };
}

And this other technique which is more 'dynamic'.

MyObject = new Object();
MyObject.aMethod= new function(){
};
MyObject.anotherMethod = new function(){
};

I have been using both of these techniques in various ways, and i understand the benefits of each, but for the life of me, I don't have any idea how to call these two techniques when discussing this with colleauges.

Do these techniques have names?

Upvotes: 1

Views: 81

Answers (2)

ljfranklin
ljfranklin

Reputation: 480

Your first example is an Object Constructor, while the second is simply adding public methods as properties to an object. As a side note, for an even more "class-like" behavior take a look at the module pattern:

var MyObject = (function() {

  var privateStaticVariable = 0;

  var my = function() {
    var self = this;

    var privateInstanceVariable = 0;

    function privateInstanceMethod() {

    }

    self.publicInstanceVariable = 0;

    self.publicInstanceMethod = function() {

    };
  };

  function privateStaticMethod() {

  };

  return my;
});

Upvotes: 2

Felix Kling
Felix Kling

Reputation: 816404

In the first case MyObject is a constructor function, since it is supposed to be called with new:

var obj = new MyObject();

In the second case, MyObject is just an object and you assign properties to it. It does not have a special name.

Note that in both cases MyObject has different values. MyObject in the second case is equivalent to obj.

A third way is to use an object initilizer or "object literal":

var obj = {
    aMethod: function(){},
    anotherMethod: function(){}
};

Upvotes: 3

Related Questions