JavaScript pass scope to another function

后端 未结 10 718
被撕碎了的回忆
被撕碎了的回忆 2020-12-23 16:48

Is it possible to somehow pass the scope of a function to another?

For example,

function a(){
   var x = 5;
   var obj = {..};
   b()         


        
10条回答
  •  南笙
    南笙 (楼主)
    2020-12-23 17:23

    You can't "pass the scope"... not that I know of.
    You can pass the object that the function is referring to by using apply or call and send the current object (this) as the first parameter instead of just calling the function:

    function b(){
        alert(this.x);
    }
    function a(){
        this.x = 2;
        b.call(this);
    }
    

    The only way for a function to access a certain scope is to be declared in that scope.
    Kind'a tricky.
    That would lead to something like :

    function a(){
        var x = 1;
        function b(){
            alert(x);
        }
    }
    

    But that would kind of defeat the purpose.

提交回复
热议问题