codetemplar
codetemplar

Reputation: 681

Javascript bind behaviour

I have two javascript files that look like:

// module1.js
var globalFunction = function(val1, val2, callback){
    var localVariable1 = val1;
    var localVariable2 = val2;
    someAsyncFunction(function(){
        callback(localVariable1, localVariable2 );
    });
}

module.exports = function(val1, val2, callback){
    var localVariable1 = val1;
    var localVariabl2 = val2;
    anotherAsyncFunction( function(){
          globalFunction(localVariable1, localVariable2, callback);
    });
}

and this:

function MyClass(val1, val2){
    this._val1 = val1;
    this._val2 = val2;
    this._boundFunc = require("./module1.js").bind(this);
}
MyClass.prototype.doSomething = function(callback){
    this._boundFunc(callback);
}

Now this incredibly contrieved example binds the module.exports to the class MyClass. What is happening under the hood here? Does each MyClass instance have its own copy of the module.exports function and also will it have it's own copy of the globalFunction as this is referenced in the module.exports?

My concern is that if multiple "doSomething" functions are called synchronously on two difference instances of MyClass then they can interfere and overwrite each others local variables whilst waiting on the asyncFunctions to callback. If the bind copied both the globalFunction and module.exports then I dont think Id have a problem. Thanks

Upvotes: 0

Views: 51

Answers (2)

sudavid4
sudavid4

Reputation: 1131

this will help you understand

Does each MyClass instance have its own copy of the module.exports function

no it doesn't. The code in module1.js is run only once and it's module.export is "cached" so whenever you require('./module1') you are getting the same instance of that object

they can interfere and overwrite each others local variables

no they can't. These variables are re-created every time you call the function so every call to the function has its own local variables and don't interfere with one another

Upvotes: 1

Bergi
Bergi

Reputation: 664256

My concern is that if multiple functions are called they can interfere and overwrite each others local variables

No, that cannot happen ever. The local variables (vars, parameters) in each function are created independently for every function call. Even if you call the same function it twice, it generates two unrelated sets of local variables. Assigning one of the variables from the first call will not change the variable of the same name in the second call.

What can of course happen is that the calls explicitly share a mutable value, i.e. an object or an instance of your class. If you change a property of it, and both function calls work on the same object, they can interfere indeed. In your example, the underscored properties of your MyClass instances are not used anywhere though.

Upvotes: 0

Related Questions