简体   繁体   中英

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

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

f is null

, then assigns tf to the newF function.

Afterwards tf is called (which is now newF ) on the same object, so tf 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 tf() ). The call is done on this line:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM