VKS
VKS

Reputation: 277

Javascript object definition

Out the following two ways, which format for defining object is good considering performance and usage:

//Object created with public members defined using this.
var object1 = function () {
  var private_i = null;
  this.public_j = null;

  //public function
  this.public_func = function () {
  }

}

OR

//Object created with public members defined using return patterns.
var object2 = function () {
  var private_i = null,
  public_j = null,

  //private function will be exposed from return statement.
  _public_func = function () {
  };

  return {
    public_func : _public_func 
  };

}

Upvotes: -1

Views: 202

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074088

The difference between the two relates to inheritance and usage. Your object2 always creates objects directly backed by Object.prototype and doesn't require use of the new keyword; your object1 creates object backed by object1.prototype (which is in turn backed by Object.prototype) and does require use of new.

Neither is really "better" in any objective way, they are just two different ways of using JavaScript, which will have fundamentally the same performance. The first one is much more common, the second one is advocated by a small but vocal minority within the JavaScript community.

The object1 example is more typically written like this:

function Object1() {
  var private_i = null;
  this.public_j = null;

  //public function
  this.public_func = function () {
  };
}

Note that the first letter in such functions is capitalized (by overwhelming convention).

The prototype thing comes into it if you're going to have functions that don't need access to private_i: You could put those on the object that will be assigned to new objects created via new Object1 like so:

function Object1() {
  var private_i = null;
  this.public_j = null;
  //public function
  this.public_func = function () {
  };
}
Object1.prototype.someOtherFunction = function() {
  // Doesn't use `private_i`
};

You can also use prototypes with your object2, like so:

//Object created with public members defined using return patterns.
var object2Prototype = {
    someOtherFunction: function() {
      // Doesn't need private_i
    };
};
var object2 = function () {
  var private_i = null,
      public_j = null,

      //private function will be exposed from return statement.
      _public_func = function () {
      };

  var obj = Object.create(object2Prototype);
  obj.public_func = _public_func;
  return obj;
};

Upvotes: 1

Related Questions