Self-executing function as object property value in javascript

Is it possible to have a self-executing function that is the value of an object property that assigns values ​​to other properties of the object?

eg. - what I would like to do is the following:

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

But the "this" inside the new function seems to refer to be. Is it possible to access the parent element of be (i.e., B) from within the function?

+6
source share
2 answers

This is how you do it.

Often called a module template ( more )

 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; } } }(); 
+7
source

You can access the value in function , you just need to get rid of new , ie

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

Source: https://habr.com/ru/post/921489/


All Articles