D
D
Denis2015-11-15 01:29:28
JavaScript
Denis, 2015-11-15 01:29:28

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, но откуда???

Please help me understand where obj != null comes from in the last x(10) call?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nikita Gushchin, 2015-11-15
@SvDenys

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.

V
Vitaly Inchin ☢, 2015-11-15
@In4in

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 question

Ask a Question

731 491 924 answers to any question