Answer the question
In order to leave comments, you need to log in
Strange behavior of JS closures. Where is the mistake?
In the process of studying closures in JS, I came across such an interesting example:
function test(ob){
return function(x){
return (ob.a + ob.b) * x
}
}
var obj = {
a : 1,
b : 2
}
var x = test(obj);
console.log(x(10)); // (1+2) * 10 = 30
obj.a = 3;
console.log(x(10)); // (3+2) * 10 = 50
obj = null;
console.log(x(10)); // вернет 50, но откуда???
Answer the question
In order to leave comments, you need to log in
obj is a reference to an object. You passed this reference to the test function (which created a copy of it, ob), and closed the anonymous function on ob. When you nullified the obj = null reference, nothing happened to the object itself and ob continues to refer to it.
In order to better understand what is happening, it is necessary to understand that
-
Thus, when there is a change in the value of a variable that refers to an object, it does not affect it in any way.
var obj = {1:0, 2:10}, ob = obj;
obj = 228;
//obj больше не ссылается на объект, теперь это просто число.
//А вот ob так и продолжает это делать
console.log(ob);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question