Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can change function scope using <code>toString()</code> and the dreaded <code>eval</code>.</p> <p>If your functions were in say lib.js as follows:-</p> <pre><code>var lib = {} lib.foo = function() { console.log(var1) } lib.bar = function() { console.log(var2) } module.exports = lib </code></pre> <p>In main.js you could have this:-</p> <pre><code>var var1 = 1 var var2 = 2 var ob1 = require('./lib') ob1.foo() ob1.bar() </code></pre> <p>When you run it the ob1.foo() line gives a ReferenceError, var1 is not defined. This is because the scope of foo() comes from lib.js and not your main js file, and var1 is invisible to it. ob1.foo is a reference to a function with lib.js scope. You need to make a new reference with main.js scope.</p> <p>To do this convert each function to string and eval it. That will create a new function with the same code but with main.js scope. Here's one way using a setMainScope method which loops through all the functions changing their scope to main.js.</p> <pre><code>var var1 = 1 var var2 = 2 var ob1 = {} ob1.setMainScope = function(ob2) { for(var prop in ob2) { if( !ob2.hasOwnProperty(prop) ) {continue} if( typeof ob2[prop] !== 'function' ) {continue} this[prop] = eval( "(" + ob2[prop].toString() + ")" ) } } ob1.setMainScope( require('./lib') ) ob1.foo() // 1 ob1.bar() // 2 </code></pre> <p>Now it all works nicely except <code>eval</code> was used. The scope of <code>foo()</code> and <code>bar()</code> is now main.js and so they 'see' <code>var1</code> and <code>var2</code>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload