Is it thread safe using variables between closures in javascript? - javascript

I was reading an article about private/protected members "emulation"
with javascript ( i know it's not a best practice but it's for research purpose )
For example, in this code we've:
var Class = (function() { // Open closure
var caller = null;
//[...]
var mayAccessWrapped = false;
function wrapmethod(method) {
mayAccessWrapped = true;
if (method.__getWrappedMethod) {
method = method.__getWrappedMethod();
}
mayAccessWrapped = false;
var wrapped = function wrapper() {
var prevCaller = caller;
caller = wrapper;
var returns;
try {
returns = method.apply(this, arguments);
}
finally {
caller = prevCaller;
}
return returns;
};
wrapped.__getWrappedMethod = function() {
if (mayAccessWrapped) { return method; }
throw "Error: only the wrapping function may access the wrapped method";
}
return wrapped;
}
//[...]
return Class;
})(); // End Class closure
"wrapped" method is used multiple times from same object and it uses caller variable to "inject" informations about the "caller" with "called" method ( alternative to deprecated arguments.callee).
But, in a concurrent scope, is this way thread safe? Is it possible that another method can change the value of caller variable invalidating data consistency?

If you literally mean "thread-safe," I think that the first question must be ... is your JavaScript interpreter thread-safe? Does it allow two or more threads to own their own interpreter-context? Is it designed with the necessary internal mutual-exclusion mechanisms to permit two or more threads to simultaneously access an interpreter's internal context/state? (And if so, are you using these facilities in exactly the prescribed way?)
If not, your program is quite certain to crash. The threads will wind up scribbling on the interpreter's internal state and "down she goes."

Related

How to monkey patch a recursive function

I'm using a library (playcanvas) that exposes a function clone() that is called recursively for all the nodes in a hierarchy.
If I monkey patch the function to execute some additional code, this will be executed multiple times.
Instead, I need to execute my code at the end of the whole recursive calls, but I can't find a way to do it.
pc.Entity.prototype.clone = function() {
... some code
// then for each child it calls itself
}
If I try this way I get "my stuff" executed multiple times.
pc.Entity.prototype.cloneOriginal = pc.Entity.prototype.clone;
pc.Entity.prototype.clone = function() {
var c = this.cloneOriginal();
// do my stuff
return c;
}
I need to "override" the clone method so that after all its recursive calls, I can execute my code.
You can achieve that by temporarily restoring the original function before launching it. And when it is finished, you set your trap again, and perform your post processing:
const orig_clone = pc.Entity.prototype.clone; // Save original clone
// Set trap:
pc.Entity.prototype.clone = function patched_clone(...args) {
pc.Entity.prototype.clone = orig_clone; // Restore original function
let result = this.clone(...args); // Execute it
// All is done, including recursion.
pc.Entity.prototype.clone = patched_clone; // Set trap again
// Your code comes here
console.log('post processing');
return result;
}
I'd still go with a simple flag to determine wether I'm inside a recursion or not.
//no need to store that function on the prototype itself
const cloneOriginal = pc.Entity.prototype.clone;
let inRecursion = false;
pc.Entity.prototype.clone = function() {
//just pass through the call to the original function.
if(inRecursion)
return cloneOriginal.call(this);
inRecursion = true;
var c = cloneOriginal.call(this);
inRecursion = false;
// do my stuff
return c;
}
inRecursion is a flag, specific for this single implementation. Maybe you want to wrap this code in a block or an iife to ensure that the variables are not accessible from outside of your clone-method.
could you point me to some more info about the optimization you are speaking about. What should I google?
You'll find most about v8 optimizations on google, but most modern browsers do similar stuff. I just googled and came across this article Performance Tips for JavaScript in V8. It's a bit older, but I think it's a good point to start getting an understanding on the kind of optimizations that JS engines do to your code to make it faster.
But as the article it mentions, don't loose yourself in (pointless) optimizations.

proper function calling etiquette?

I may be wording this title wrong but in javascript is it ok to call a nested function like so, if not why and what are some safer or more proper ways
function foo() {
return function poo() {
console.log("ew");
}
}
var fooPoo = foo()();
Yes, that's fine, and fairly normal, if you want poo to have access to information that's private within foo and you don't want the calling code to have access to that information. Or even just if foo is what knows how to create the poo function, even if private information isn't needed.
It's relatively rare to do it all in one expression, because usually when you return a function from another function, you want to keep the function around:
var p = foo();
var fp1 = p();
var fp2 = p();
...but only relatively unusual, not unusual.
Here's an example of using the private information held by the context of the original call to the function (allocator, here, is like your foo):
function allocator(seed) {
return function() {
return seed++;
};
}
var a = allocator(1);
console.log(a()); // 1
console.log(a()); // 2
console.log(a()); // 3
Note that the code calling a can't manipulate seed directly. It can only call a and use the value it returns.
Yes, it as a functional technique referred to as currying. it allows you to set parameters for the function in different places in your code
function foo(param1) {
return function poo(param2) {
console.log(param1, param2);
}
}
var fooPoo = foo('param1')('param2');
A common thing I do is use currying for passing in settings when running event listeners to allow greater reuse of functions
function setColor(color) {
return function (e) {
e.target.background = color
}
}
someElement.addEventLister('click', setColor('red'))
Here you can pass in your configuration when declaring your event listener but it won't be called until later when the event is fired and due to the closure you will have access to the color variable within the event listener callback. But now that I know the technique I use it quite a bit

Is it possible to get the local variable and parameter values with window.onerror

I have a simple javascript error logging mechanism in place and it looks somewhhat like this:
window.onerror = function (ErrorMsg, Url, LineNumber, Col, Error) {
// ajax these to the server, including Error.stack}
The problem is that I'd also like to get the value of the local variables and function parameters when the error occurred. Is this even possible?
I'm thinking about modifying the Function prototype so that each time a function runs, its arguments are stored in a global array of strings and then the error handler would just add this array to the ajax call. Can JavaScript do this?
#1 Can local scope be recovered in onerror() without black magic?
Without this being bound in the scope of window.onerror() or the surrounding variables being directly accessible, it's impossible to regain access to the variables you had set.
What you're mostly wanting access to is this.arguments or arguments or the equivalent, but that's destroyed. Any hope of obtaining a key-value associative array or hash-like object would involve meta-programming ( i.e. reading the function definition to obtain the variable names, and obtaining an exception report to attempt to salvage data ).
See this answer for more on something similar:
Getting All Variables In Scope
But this "lacking functionality" is a good thing:
If you could gain access to what you're asking for, that would likely be a fault in the Javascript engine. Why? Because the variable states and contents themselves are what caused the exception/error, assuming bad code wasn't the issue to begin with.
In other words, if you could get access to a faulty variable, that might be a door into an infinite loop:
Failure due to variable contents.
Error handler triggered.
Trace contents of variable.
Failure due to variable contents.
Error handler triggered.
Trace contents of variable.
Etc.
#2 Can Javascript store all arguments of every function call by voodoo?
Yes. It can. This is probably a really bad idea ( see #1 ) but it is possible. Here is a pointer on where to start:
Is there a way to wrap all JavaScript methods with a function?
From there, what you're wanting to do is push this.arguments or equivalent to a stack of function calls. But again, this is approaching insanity for many reasons. Not the least of which is the need to duplicate all the values, lest you reference mutated variables, or be unable to access the data at all... and like I said above, the problem of bad data in general. But still, it is possible.
Is this even possible?
No. A stack trace is proof that the stack has unwound, all stack frames and all the local variables they contained are gone. As for getting the name of a variable, that is not even possible at run time.
To start off i accept #Tomalak completely.
I was also put in your situation where i needed to debug a remote running app in case of crash.
As a work around I have forked my code for you in a fiddler. Please modify according to your need.
Caveat: You have to wrap the function body with try{..}catch(e){..} as illustrated in the fiddler code.
Please read the inline comments for understanding.
window.onerror = function (errorMsg, url, lineNumber, column, errorObj) {
console.log(errorObj);
}
window.addEventListener("reportOnError", function(e){
console.log(e.detail);
/*Send to the server or any listeners for analysis.*/
//Http.send(e.detail);
});
function ExceptionReport(ex, args, scope) {
var self = {};
self.message = ex.message;
self.stack = ex.stack;
self.name = ex.name;
self.whoCalled = args.callee.caller.name == "" ? "Window": args.callee.caller.name;
self.errorInFunction = args.callee.name;
self.instanceOf = scope.constructor;
self.KeyPairValues = getParamNames(arguments.callee.caller.toString(), Array.prototype.slice.call(args)); //Contains the parameters value set during runtime
window.dispatchEvent(new CustomEvent('reportOnError', {'detail':self}));
}
//Utilties
function getParamNames(fnBody, values) {
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg,
ARGUMENT_NAMES = /([^\s,]+)/g,
result = fnBody.slice(fnBody.indexOf('(')+1, fnBody.indexOf(')')).match(ARGUMENT_NAMES),
obj={};
fnBody.replace(STRIP_COMMENTS, '');
if(result !== null){
for(var i=0; i < result.length; i++){
obj[result[i]] = values.length !==0 ? values[i] : null;
}
}else{
obj = null;
}
return obj;
}
/*
This is a testing/sample function that throws the error
*/
function testing(a,b,c){
try{
dummy(1,2) ; //This line throws the error as reference error.
}catch(e){
ExceptionReport(e, arguments, this);
}
}
//Class Emulation: For instanceof illustration.
function testingClass(){
this.testing = testing;
}
//Named self executing function: This calls the function
var myvar = (function myvar(){
testing(1,2,3);
})();
//Illustrating instanceof in exception
var myVar2 = new testingClass();
myVar2.testing(1,2,3);
//Calling from global scope this is Window
testing(1,2,3);
//Without variables
testing();
I have used examples to illustrate the behavior of functions called in different circumstances.
Below signifies the varialble used for
self.KeyPairValues : Used to store the function parameter set/passed during runtime
self.errorInFunction : This stores the name of the function error was caused in.
self.whoCalled : This stores the function name that invoked the defective function
self.instanceOf : This stores the name of the instance is called creating a new instance.
Other variables are same as in Error object
The others answers here are spot on, but I might be able to offer a suggestion for a slightly different way to accomplish this. Instead of trying to track all scope in your program, why not add a tagging function that tracks the scope of one function's parameters without affecting the runtime of the function. For for example:
var globalRecord = {};
function record(name, fn) {
return function () {
var args = [].slice.call(arguments);
var record = globalRecord[name] = {
args: args,
arg: {}
};
args.unshift(function (name, value) {
return record[name] = value;
});
fn.apply(args, arguments);
}
}
// Then, you track variables like this
var func = record("func", function (record, a, b, c) {
record("a", a); // named parameters are accessible now
record("b", b); // if some error occurs in the function body
return a + b + c;
});
// Calling func still behaves as before.
func(1, 2, 3);
// Errors handled like this:
window.onerror = function () {
globalRecord.func.args; // ==> last set of arguments past to function
globalRecord.func.arg.a; // specific arguments recorded with names
};
You could even use this method to track scope without using a function by anonymously calling the recorded function.
record("test", function (record) {
var a = record("a", /* whatever */);
var b = record("b", /* ... */ );
// do scope specific stuff that might fail
})();
Of course, this isn't a polished implementation by any stretch, but with a little work, I think you might be able to get the behavior you're looking for without any seriously black magic. By selectively adding and removing record calls as the need presents itself, you can have precise control over what is logged without any intrusive hacks.
You can find your answer in this link.
Before taking bundles from the server, you must modify them. For example, to solve your problem, you can do changes in the mentioned link as follows. In the BuildBundleContent Class make this change:
contents.Insert(blockContentIndex,
string.Format("if(customErrorLogging)customErrorLogging({0}, this){1}",
errVariable, hasContent ? ";" : ""));
If in the modules you have to use something like:
var self = this;
You can use:
contents.Insert(blockContentIndex,
string.Format("if(customErrorLogging)customErrorLogging({0}, self ? self : this){1}",
errVariable, hasContent ? ";" : ""));
And in added js file:
"use strict";
var customErrorLogging = function (ex, module) {
console.log(module);
//do something...
};
I hope help you.

Elegant callback binding when using promises and prototypes in javascript

I am an heavy javascript prototypes and promises user.
My problem is that I need to use .bind(this) to set the right context about every time I thenify my promises.
Here is a sample code showing the problem (jsbin):
var Q = require('Q');
var AsyncCounter = function(initialValue){
this.value = initialValue;
};
AsyncCounter.prototype.increment=function(){
return Q.fcall(function(){
return ++this.value;
}.bind(this));
};
AsyncCounter.prototype.decrement=function(){
return Q.fcall(function(){
return --this.value;
}.bind(this));
};
var counter = new AsyncCounter(10);
counter.increment()
.then(function(incrementedValue){
console.log('incremented value:', incrementedValue)
})
.then(counter.decrement.bind(counter))
.then(function(decrementedValue){
console.log('decremented value:', decrementedValue)
});
See how often I have to rely on bind()? I find it too unelegant.
I do know about petkaantonov/bluebird promise library and its very useful bind(scope) function that propagate the scope on callbacks but I feel like there is a better, native way to do it.
Does anybody have a proper way to do it?
Remember when you learned about Foo.prototype.bar=function(){...} and turned your back on defining methods inside the constructor as this.bar = function(){...}? The reasons were speed, and efficiency of memory.
Well now you have good reason to turn the clock back and sacrifice speed/efficiency in order to achieve "detachable" methods - ie methods that are specific to their instance of the constructor with this ready bound, which is exactly what you want.
If the methods are called many times, then the inefficiency of construction will be more than compensated for by not having to use bind() when referring to the function. Plus you get the syntactic convenience you seek.
Here's a version of your example re-jigged to better demonstrate the syntactic convenience :
var AsyncCounter = function(value){
this.increment = function(){
return Q.fcall(function(){
return console.log("++value: " + ++value);
}.bind(this));
}.bind(this);
this.decrement = function(){
return Q.fcall(function(){
return console.log("--value: " + --value);
}.bind(this));
}.bind(this);
};
var counter = new AsyncCounter(10);
counter.increment()
.then(counter.decrement)
.then(counter.increment);
In summary, you need to do two things :
define methods inside the constructor
bind this to the methods.
I think another way to do it is by taking advantage of closures. Every callback that is used in the promise can contain references to some variables of the root scope where it was created.
Normally what most of the people do is to create a variable called self that maintans a reference to the outer this. So wherever you execute the function of the promise, the closure will maintain the reference and therefore be able to access the scope.
AsyncCounter.prototype.increment=function(){
var self = this;
return Q.fcall(function(){
return ++self .value;
});
};
Honestly, I'm not sure which one is more elegant. I'm not sure if there are any other ways of doing what you want without using this technique or the bind method.
The best solution in my opinion is to add a context method to promises to specify the this for function calls in future then invocations. This is something I seem to recall having seen in some libraries, can't remember where, and implemented in my own as well. The idea is to write
promise.context(this).then(myfunc)
I don't know Q, so I don't know if it would be easy or even possible to extend it/customize it to have this behavior. Here is a toy implementation of this idea using native JS promises:
Promise.prototype.context = function (ctxt) { this.ctxt = ctxt; return this; }
Promise.prototype.then = (function() {
var old_then = Promise.prototype.then;
return function(fulfill, reject) {
return old_then.call(this,
fulfill && fulfill.bind && fulfill.bind(this.ctxt),
reject && reject.bind && reject.bind(this.ctxt)
);
};
}());
Actually, you can often write your code so that it doesn't end up littered with context calls, by doing it once where you create the promise. So:
var MyTrip = {
gotoMars: function() { return InterPlanetaryTrip(Mars).context(this); },
report: function() { console.log("I'm back, Mom!"); },
go: function() { gotoMars.then(this.report).then(this.drink); }
};
This approach saved me boundless aggravation and has zero downsides that I can see. I cannot see a more "native" way to do this, whatever that might mean.
Less intrusive approach?
As a more direct answer to your question, you could possibly introduce a small bit of sugar--a method which binds and calls Q.fcall in one fell swoop, as follows:
AsyncCounter.prototype.fcall = function(fn) {
return Q.fcall(fn.bind(this));
};
AsyncCounter.prototype.increment = function() {
return this.fcall(function() {
return ++this.value;
});
};
If you're using ES6 you could use arrow functions and use the lexical scope.
AsyncCounter.prototype.increment = () => {
return Q.fcall(() => ++this.value);
};

Distinguish between a constructor and a normal function

I'd like to call a function without knowing how it should be called/instantiated. For my understanding there are two ways we can either use new Foo() or Foo().
As I need a wrapper to call this function, let's say it's basically a proxy. I have a reference to a function but don't know in which way I should call it, wether it is meant to be a constructor or a plain javascript function.
As it seems that there is no way to distuingish between both ways I came up with the following.
var delegate;
var Foo = function() { };
Foo.prototype.foo = function() { alert("foo") };
var bar = function(value) { alert(value); }
function construct(constructor, args) {
function F() {
return constructor.apply(this, args);
}
F.prototype = constructor.prototype;
return new F();
}
var proxy = function() { return construct(delegate, arguments) };
delegate = bar;
proxy("bar");
delegate = Foo;
new proxy().foo();
This gives me the expected result and seems to work. Do you see anything bad with this solution? Is it bad to call a regular function with new? What are the downside of this technique?
The code is based on the following question "Use of apply with the new operator"
Is it possible to distinguish between a constructor and a normal function?
No. Every normal (user-defined) javascript function can act as both. From inside the function, you might do some reasoning depending on how the this value looks like, but this is not reliable.
See also How to detect if a function is called as constructor?
I have a reference to a function but don't know in which way I should call it, wether it is meant to be a constructor or a plain javascript function.
However, you don't need to know that - proxy itself is called as either as a constructor or plain function by someone who knows it.
Do you see anything bad with my solution?
That closure over delegate which is later changed is ugly when left in the open. In your case you don't really seem to need it, a plain proxy = bar; and proxy = Foo; would be sufficient there. Also, your construct function looks unnecessary.
Is it bad to call a regular function with new? What are the downside of this technique?
If the function does not use this, then no problems will arise, but there's overhead in constructing the instance object.
For a proxy function that is passed somewhere else (so that we cannot easily change the reference), I'd use an explicit setter for delegate:
function makeProxy(delegate) {
function proxy() {
return delegate.apply(this, constructor);
}
proxy.prototype = delegate.prototype;
return {
proxy: proxy,
setTarget: function(d) {
delegate = d;
proxy.prototype = d.prototype;
}
};
}
var p = makeProxy(bar);
p.proxy("bar");
p.setTarget(Foo);
new (p.proxy)().foo();

Categories