简体   繁体   中英

Javascript: unique inner function “remembers” outer function first call arguments?

Using this code

this.outerFn = function(param)
{
    this.currentParam = param;
    if(!this.hasInnerFn)
    {
        this.innerCallFn = function()
        {
            console.log('param: ' + param.toString() + ' ; this.currentParam: ' + this.currentParam);
        }
        this.hasInnerFn = true;
    }

    setTimeout(function(){
        this.innerCallFn();
    },1000)
}

and calling:

this.outerFn('param 1')
this.outerFn('param 2')

gives the following results:

param: param 1 ; this.currentParam = param 1
param: param 1 ; this.currentParam = param 2

Why at the second call to innerCallFn does it reference the outer function's first parameter ?

innerCallFn is created only once, so won't it see as 'param' only its value at the first call ? In other words, does every function call have its own closure ?

实际上,内部函数使用的param值实际上是在第一次创建该函数时绑定一次。

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