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

前端 未结 10 1458
北荒
北荒 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-16 11:35

    You can use WebWorkers to isolate your code:

    Create a completely separate and parallel execution environment (i.e. a separate thread or process or equivalent construct), and run the rest of these steps asynchronously in that context.

    Here is a simple example:

    someGlobal = 5;
    
    //As a worker normally take another JavaScript file to execute we convert the function in an URL: http://stackoverflow.com/a/16799132/2576706
    function getScriptPath(foo) {
      return window.URL.createObjectURL(new Blob([foo], {
        type: 'text/javascript'
      }));
    }
    
    function protectCode(code) {
      var worker = new Worker(getScriptPath(code));
    }
    
    protectCode('console.log(someGlobal)'); // prints 10
    protectCode('console.log(this.someGlobal)');
    protectCode('console.log(eval("someGlobal"))');
    protectCode('console.log(window.someGlobal)');
    

    This code will return:

    Uncaught ReferenceError: someGlobal is not defined

    undefined

    Uncaught ReferenceError: someGlobal is not defined and

    Uncaught ReferenceError: window is not defined

    so you code is now safe.

提交回复
热议问题