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!
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!
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
setTimeout can be any asynchronous function or event - GrundySource: https://ru.stackoverflow.com/questions/620856/
All Articles
salecall, the link to theproductstill undefined. It is obvious. Those. you must first return theproductlink from somewhere. - Sublihimjobvariable is assigned the value - Vladimir