Igor Seliverstov
Igor Seliverstov

Reputation: 547

javascript: null variable in function changes its value?

Can a null variable in a function become not null? When f enters in function chainF it somehow changes its value? It isn't null anymore.

function TestF(){}

TestF.prototype = {
    i: 0,
    f: null,
    chainF: function(g){
        if(this.f == null)
            console.log('f is null');
        var newF = function(){
            if(this.f == null)
                console.log('f is null');
                g();
        };
    this.f = newF;
    return this;
    }
}

t = new TestF();
t.chainF(function(){console.log('g')}).f();

Output: f is null (only once) g

Upvotes: 0

Views: 76

Answers (1)

Tibos
Tibos

Reputation: 27843

When chainF is called, it goes in the first if and outputs

f is null

, then assigns t.f to the newF function.

Afterwards t.f is called (which is now newF) on the same object, so t.f is not null. The next thing to do is call g(), outputting

g

Maybe the misunderstanding is that when you declare the newF function you also think the code is executed. It is not, the function is assigned to newF and will be run when it is called (newF() or t.f()). The call is done on this line:

t
  .chainF(function(){console.log('g')})
  .f();                                   // here

Upvotes: 1

Related Questions