如何从定义函数而不是调用对象访问变量状态

Sys*_*ral 1 javascript

例如:

func = (){

    var i_want_this = "yes";

    var callback = function(){
        // I want to access value of i_want_this here
        // Preferably just the single variable without the whole scope
    };

    obj.subfunc(some_stuff, callback);

};


obj = {

    subfunc = function(stuff, callback){

        // do stuff

        callback();

    }

};

func();
Run Code Online (Sandbox Code Playgroud)

SLa*_*aks 5

您可以在回调中使用该变量; 它会以你想要的方式工作.

这称为闭包.