How do I declare objects so that the following code works? (so that the product variable has properties and not undefined)

var product = Factory.createProduct().sale(function() { console.log(product.id) }); 

Thank you in advance!

  • at the time of the sale call, the link to the product still undefined. It is obvious. Those. you must first return the product link from somewhere. - Sublihim
  • From the point of view of the product program, @Sublihim can be defined if the sale returns something, and a callback occurs after the sale is completed. For the rest, it remains only to guess what the author has and how. - user220409
  • I understand this, but it is not very clear to me why, for example, such code works and at what point the job variable is assigned the value - Vladimir
  • @OlmerDale wonders how you will call a callback after return? - Sublihim
  • @Sublihim I don’t even know what to say, there are just a lot of options and each of them is common for js. That is, this question is generally the very basics of the language. And I don’t even know the author what to advise. I do not want to follow the links and understand someone else's code, then to explain what is written in all books. And according to the code shown, one can only guess ... Therefore, in my opinion, a difficult situation in which only I can help. - user220409

1 answer 1

I will give one of the examples.
Let's simplify the example to make it clearer:

 function sale(callback) { if (callback) { setTimeout(callback, 100); } return { id: 'some_id' }; }; var product = sale(function() { console.log('in callback: ' + product.id); }); console.log('simple log: ' + product.id); 

Here the function object was passed to the sale function, which sort of "captured" the execution area that contains the product . This is called closure.

In the end, the value of product was assigned, and then the callback, which contained a link to product , was executed on timeout

  • one
    instead of setTimeout can be any asynchronous function or event - Grundy
  • Yes, timeout, I gave, as the most accessible example - Sublihim