简体   繁体   中英

Can I pass this function to another function in Javascript?

I wrote this, but not work

Can javascript function pass self to other function

Can I also access the variable in the caller function?

function caller()
{
    var variable=123;
    calledfunction(this);
}
function calledfunction(caller)
{
    console.log(caller.variable);
}
caller();

Change var variable in the assignment to this.variable :

function caller()
{
    this.variable=123;
    calledfunction(this);
}
function calledfunction(caller)
{
    console.log(caller.variable);
}
caller();

In this case caller is not really generating a new instance/scope so this is actually global which is bad. It would be better to create a new empty object and use that to hold data instead of using this .

function caller()
{
    var data = {};
    data.variable=123;
    calledfunction(data);
}
function calledfunction(values)
{
    console.log(values.variable);
}
caller();

Alternatively you can use a closure in this case by putting calledfunction inside caller :

function caller()
{
    var variable=123;
    calledfunction();

    function calledfunction()
    {
        console.log(variable);
    }
}
caller();

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