0

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

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.