7

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?

5
  • I can't see why you'd want to instantiate an anonymous function as you currently are. Commented Jul 27, 2012 at 12:44
  • What is your end goal here? To execute code during the object's creation that edits other properties of the object? Commented Jul 27, 2012 at 12:44
  • @jackwanders - yep. I was just wondering if it was possible to do it this way as a sort of shortcut to jakeclarckson's method below. Commented Jul 27, 2012 at 12:50
  • Work with functions! They are first-class objects in javascript, so they are very powerful. Never use the new operator! (Except for selfmade objects) Also you should read something about scope and closures in Javascript. Commented Jul 27, 2012 at 12:53
  • @Christoph I tried it using (function(){}()) but "this" inside the function referred to the Window object rather than b using the new operator seemed to be the only way to get access to b inside the function. Commented Jul 27, 2012 at 12:59

2 Answers 2

7

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;
     }
   }
}();
Sign up to request clarification or add additional context in comments.

Comments

1

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

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

2 Comments

Yeah but that wont assign the value to b.d unless I call b.e(). I was hoping to use a self executing function to do it.
But then you have to explicitely call b.e() - this binds e to the the object b. Which is not the case with a selfexecuting function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.