Calling toString on a javascript function returns source code

前端 未结 6 1288
梦如初夏
梦如初夏 2020-12-14 06:06

I just found out that when you call toString() on a javascript function, as in myFunction.toString(), the source code of that function is returned.

If y

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-14 06:43

    You can use it to create a Web Worker from function defined in the main script:

    onmessage = function(e) {
      console.log('[Worker] Message received from main script:',e.data);
      postMessage('Worker speaking.');
    }
    
    b = new Blob(["onmessage = " + onmessage.toString()], {type: 'text/javascript'})
    
    w = new Worker(window.URL.createObjectURL(b));
    
    w.onmessage = function(e) {
        console.log('[Main] Message received from worker script:' + e.data);
      };
    
    w.postMessage('Main speaking.');
    

提交回复
热议问题