Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Self executing function as object property value in javascript

Tags:

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?

like image 473
JJ_ Avatar asked Jul 27 '12 12:07

JJ_


People also ask

Can a function be a property of an object JavaScript?

Methods—setting functions as properties of objects. In JavaScript, you can use functions as values, just like numbers, strings, and objects. That means you can pass them as arguments, return them from other functions, and set them as properties of objects.

What is a self executing function in JavaScript?

A JavaScript function that runs as soon as it is defined. Also known as an IIFE (Immediately Invoked Function Expression).

Can an object value be a function JavaScript?

An object is a collection of properties, and a property is an association between a name (or key) and a value. A property's value can be a function, in which case the property is known as a method.

How do you assign a value to an object property?

Object.assign() Method Among the Object constructor methods, there is a method Object. assign() which is used to copy the values and properties from one or more source objects to a target object. It invokes getters and setters since it uses both [[Get]] on the source and [[Set]] on the target.


2 Answers

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;
     }
   }
}();
like image 83
Hogan Avatar answered Oct 06 '22 00:10

Hogan


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

e: function () {
    this.d = 5;
}
like image 23
jabclab Avatar answered Oct 06 '22 00:10

jabclab