Recovering Nerdaholic
Recovering Nerdaholic

Reputation: 707

Is it possible to use a constructor in a Javascript object literal to avoid instantiation?

I have an object that needs certain properties to be set by execution instead of assignment. Is it possible to do this using a literal object notation?

I would like to be able to access the object's properties using this:

myObject.propertyName

...rather than this:

objInstance = new myObject();
objInstance.propertyName;

EDIT: to clarify, based on Bergi's answer, this is what I'm aiming to do:

var myObj = {
    myInfo: (function() { return myObj.getInfo('myInfo'); })(),
    getInfo: function() { 
      /* lots of execution here that would be redundant if done within myInfo */
    }
}

// access the calculated property value
myObj.myInfo;

But this gives me the error myObj is not defined

Upvotes: 0

Views: 55

Answers (2)

Recovering Nerdaholic
Recovering Nerdaholic

Reputation: 707

Thanks to Bergi to finding this, here is a final example what I wanted to do:

myObj = {
   init: function() {
        this.oneProperty = anyCodeIWant...
        this.anotherProperty = moreCodeIWant...
        // and so on
        return this;
   }
}.init();

myObj.oneProperty;
myObj.anotherProperty;
// and so on

Upvotes: 0

Bergi
Bergi

Reputation: 664620

I guess what you want is an IEFE, which you can put inside an object literal:

var myObject = {
    propertyName: (function() {
        var it = 5*3; // compute something and
        return it;
    }()),
    anotherFunction: function() {…}
};

myObject.propertyName // 15

Maybe you also want to use the module pattern. Have a look at Simplest/Cleanest way to implement singleton in JavaScript?.

Upvotes: 2

Related Questions