Confused. I am trying to create an object that should initialize itself. Alas, there are gaps in my knowledge.

var obj = { // params, functions... init : (function(){ alert(obj); })() } 

Alas, undefined is displayed, i.e. The object has not yet been created, but the function has already been called. How to solve this problem? It is possible so:

 ... init : function(){ alert(obj);} } 

And cause artificially:

 obj.init() 

However, I would like to automate the process ...

    1 answer 1

    The assignment calculation model lvalue = rvalue is as follows: first, the rvalue is executed and only then the result is assigned to the lvalue. That is, it makes no sense to refer from the right expression to the left one, since nothing has been assigned to it yet and it is undefined.

    In the right expression to get a link from the unfinished object to the most impossible, so your idea will not work. In addition, it is not clear why and where it may be useful at all?

    But you can do the following:

    1 - call the function after building the object

     var obj = ({ init:function(param2){ this.a=10; this.b=param2; return this; } }).init(20) 

    2 - instead of an object, create a function that returns an object

     var obj = (function(param2){ return { a:10, b:param2 }; })(20); 

    3 - for automation it is better to learn OOP and use it.

     function Obj(param1, param2){ this.a=param1; this.b=param2; } a = new Obj(1,2); b = new Obj2(10,20); 
    • @ Alexey123, your first answer suits me. 2nd -? 3rd - OOP is studied, so I used this template before, but at the moment I wanted to create an object through a literal. Why and where can be useful? My object creates a div element and I would like this div to be added to the DOM without calling additional methods.))) - Deus
    • Just from my vision of the question, an object is created that is no different, as if it was created through an ordinary literal. That is, in the end, in all three cases, the object is {a: 10, b: 20}, which could have been created by directly prescribing the properties, without inventing additional difficulties. Therefore, I have a question about expediency, where it can really help. Well, except for the third option, there is the creation of several objects based on the template. - Alex Krass
    • @Alexey123, well, I just never used the internal initialization of the object, so I was surprised that the called function inside the object still does not know about its properties, even if they are declared BEFORE the self-calling function. Your second option was also on my mind, but I asked a question to clarify this behavior for myself. In my case, the object creates an invisible div, which should itself place itself in the document tree and wait for the other methods and properties to be called. That's all. - Deus