I’m trying to redefine the function, but the behavior is not clear:
function START() {new net.Server((c)=>{SOCK(c)}).listen(80);}
function SOCK(c) {c.on('data',(t)=>{DATA(t)});}
Option 1 of the function declaration:
function DATA(t) {} – after redefinition new data is processed by the old version of the function
Option 2 of the function declaration:
var DATA=function(t) {} – after redefinition new data is processed by the new version of the function
Why in option 1 after redefining the function in the ‘data’ event handler the old version of the function is called?..
I expect both options to call the new version of the function.
Run the code in vm context then change the DATA function and update it in the same context
function START() {new net.Server((s)=>{s.on('data',(t)=>{DATA(t);});}).listen(8080,()=>{var c=new net.Socket().connect(8080,()=>{setInterval(()=>{c.write('12345');},1000);});});}
function DATA(t) {console.log(t.toString());}
var started; if(!started) {started=1; START();}
function START() {new net.Server((s)=>{s.on('data',(t)=>{DATA(t);});}).listen(8080,()=>{var c=new net.Socket().connect(8080,()=>{setInterval(()=>{c.write('12345');},1000);});});}
var DATA=function(t) {console.log(t.toString());}
var started; if(!started) {started=1; START();}
In the first case, the old version of the function will be called by the ‘data’ event, in the second case – the new one. Why is the old version of the function called in the first case?
This can only be explained by the fact that the reference to the function is strictly saved in the context of the event handler execution.
But at the same time, if the function is called from, for example, setInterval(()=>{DATA()},1000), then in both versions of the function override, the new version of the function is always called.
That is, in the case of setInterval(()=>{DATA()},1000), the DATA function is always called from the global context, and by the event c.on(‘data’,(t)=>{DATA(t)}); it is called from the local one, the question is why is this so…
User Mail is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.