Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript constructors using JavaScript object literal notation

What is the best way to build constructors in JavaScript using object literal notation?

var myObject = {
 funca : function() {
  //...
 },

 funcb : function() {
  //...
 }
};

I want to be able to call

var myVar = new myObject(...);

And pass the arguments to a constructor function inside myObject.

like image 259
mrwooster Avatar asked Mar 03 '11 10:03

mrwooster


2 Answers

This is not "JSON notation", this is JavaScript object literal notation. JSON is only a subset of JS object literal notation, but apart from looking similar, they have nothing in common. JSON is used as data exchange format, like XML.

It is not possible what you want to do.

var myObject = {};

creates already an object. There is nothing what you can instantiate.

You can however create a constructor function and add the methods to its prototype:

function MyObject(arg1, arg2) {
    // this refers to the new instance
    this.arg1 = arg1;
    this.arg2 = arg2;

    // you can also call methods
    this.funca(arg1);
}

MyObject.prototype = {
 funca : function() {
  // can access `this.arg1`, `this.arg2`
 },

 funcb : function() {
  // can access `this.arg1`, `this.arg2`
 }
};

Every object you instantiate with new MyObject() will inherit the properties of the prototype (actually, the instances just get a reference to the prototype object).

More about JavaScript objects and inheritance:

  • Working with objects
  • Details of the object model
  • Inheritance revisited

Update2:

If you have to instantiate many objects of the same kind, then use a constructor function + prototype. If you only need one object (like a singleton) then there is no need to use a constructor function (most of the time). You can directly use object literal notation to create that object.

like image 154
Felix Kling Avatar answered Oct 30 '22 02:10

Felix Kling


Make the object a function, like this:

var myObject = function(arg1){
  this.funca = function(){
    //...
  };
  this.funcb = function(){
    //...
  };
  this.constructor = function(obj){
    alert('constructor! I can now use the arg: ' + obj.name);
  };
  this.constructor(arg1);
};

// Use the object, passing in an initializer:
var myVar = new myObject({ name: 'Doug'});
like image 30
Simeon Avatar answered Oct 30 '22 04:10

Simeon