Is it possible to restrict the scope of a javascript function?

前端 未结 10 1454
北荒
北荒 2020-12-16 10:50

Suppose I have a variables in the global scope.

Suppose I wish to define a function which I can guarantee will not have access to this variable, is there a

10条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-16 11:26

    EDIT: This answer does not hide the window.something variables. But it has a clean way to run user-defined code. I am trying to find a way to mask the window variables

    You can use the javascript function Function.prototype.bind() to bind the user submitted function to a custom scope variable of your choosing, in this custom scope you can choose which variables to share with the user defined function, and which to hide. For the user defined functions, the code will be able to access the variables you shared using this.variableName. Here is an example to elaborate on the idea:

    // A couple of global variable that we will use to test the idea
    var sharedGlobal = "I am shared";
    var notSharedGlobal = "But I will not be shared";
    
    function submit() {
      // Another two function scoped variables that we will also use to test
      var sharedFuncScope = "I am in function scope and shared";
      var notSharedFuncScope = "I am in function scope but I am not shared";
    
      // The custom scope object, in here you can choose which variables to share with the custom function
      var funcScope = {
        sharedGlobal: sharedGlobal,
        sharedFuncScope: sharedFuncScope
      };
    
      // Read the custom function body
      var customFnText = document.getElementById("customfn").value;
      // create a new function object using the Function constructor, and bind it to our custom-made scope object
      var func = new Function(customFnText).bind(funcScope);
    
      // execute the function, and print the output to the page. 
      document.getElementById("output").innerHTML = JSON.stringify(func());
    
    }
    
    // sample test function body, this will test which of the shared variables   does the custom function has access to. 
    /* 
    return {
            sharedGlobal : this.sharedGlobal || null,
             sharedFuncScope : this.sharedFuncScope || null,
           notSharedGlobal : this.notSharedGlobal || null,
             notSharedFuncScope : this.notSharedFuncScope || null
     }; 
    */
    
    

    Add your custom body here



    The example does the following:

    1. Accept a function body from the user
    2. When the user clicks submit, the example creates a new function object from the custom body using the Function constructor. In the example we create a custom function with no parameters, but params can be added easily as the first input of the Function constructor
    3. The function is executed, and its output is printed on the screen.
    4. A sample function body is included in comments, that tests which of the variables does the custom function has access to.

提交回复
热议问题