JJ_
JJ_

Reputation: 174

Self executing function as object property value in javascript

Is it possible to have a self executing function which is an objects property value assign values to other properties in the object?

e.g. - what I would like to do is this:

var b={
  c:'hi',
  d:null,
  e:new function(){this.d=5}
};

But the "this" inside the new function seems to refer to b.e. Is it possible to access the b.e parent (i.e. b) from inside the function?

Upvotes: 7

Views: 4559

Answers (2)

Hogan
Hogan

Reputation: 70538

This is how you do it.

Often called the module pattern (more info)

var b = function () {
   var c = 'hi';
   var d = null;

   return {
     c : c,
     d : d,
     e : function () {
       // this function can access the var d in the closure.
       d = 5;
     }
   }
}();

Upvotes: 7

jabclab
jabclab

Reputation: 15062

You can access the value within the function, you just need to get rid of the new, i.e.

e: function () {
    this.d = 5;
}

Upvotes: 1

Related Questions