Creating functions that have side effects (in-place) from prototypes that are not
I want to wrap some prototypes without using return values.
The following code returns a sorted list in modern browser developer consoles:
Array.prototype.sor = function() {
Array.prototype.sort.apply(this);
};
var t = [2,3,1]
t.sor()
t
As below:
sor = function(l) {
Array.prototype.sort.apply(l);
};
var t = [2,3,1]
sor(t)
t
Is it also possible to call effects in place on an array (like sor
) using non-in-place prototypes that return their result, for example join
, for strings, trim
or replace
?
For example, for example:
String.prototype.tri = function() {
String.prototype.trim.apply(this);
};
var t = " 123"
t.tri()
t
Which ideally returns "123"
in the browser console (new value for t
). This is not the case since it String.prototype.trim
returns a value that is never matched. But of course I can't just set this
to the trimmed string:
this = String.prototype.trim.apply(this);
source to share
The only way I can think of is using context and referring to your variable using bound notation context['nameOfVar']
.
This can be done because a JS variable is nothing but an Object property.
If variables are always declared in the global scope, you can do window['myVar']
, but to make sure it applies in any scope it would be better to use this['myVar']
.
I'm not sure if it's dangerous or not, I just find it hacky. If anyone knows, tell us! :)
var joinMe = function(separator, prop) {
this[prop] = this[prop].join(separator);
};
t = [2,3,1];
joinMe(',', 't');
document.body.innerHTML = t; // "2,3,1"
source to share