I want to know if it is possible to somehow "bind" a javascript arrow function to an instance of the prototype to which it is scoped.
Basically, I want to get an instance variable from a prototype using an arrow function. I know this cannot be done by arrow function alone, but I am curious if it is possible to also bind this arrow function to the instance scope before assigning it. Something along the idea of:
String.prototype.myFunction = (() => {
console.log(this.toString());
}).naiveBindNotionICantDescribe(String.prototype);
which would be equivalent to:
String.prototype.myFunction = function() {
console.log(this.toString());
};
I am curious because I am trying to see if javascript arrow functions can completely replace javascript functions if you understand them well enough and are clever with them, or if there are things which are absolutely impossible to accomplish without keyword "function", even in clever ways.
Here is an example of what I mean:
/* anonymous self-contained demo scope. */
{
/**
* example #1: using function to reach into instance variable via prototype
* anonymous scope.
*/
{
String.prototype.get1 = function() {
return this.toString();
};
console.log('hello'.get1());
}
/**
* example 2: what I want to do but can't express in a way that works.
* This does not work.
* anonymous scope.
*/
{
String.prototype.get2 = () => {
return this.toString();
};
console.log('hello'.get2());
}
}
Is this possible to do, or are functions absolutely necessary to reach into instance variable and there is no way to circumvent this?
Apparent Solutions:
- wrapper magicBind (Thanks Thomas)
code:
var magicBind = (callback) => function() {
return callback(this);
};
String.prototype.get = magicBind((self) => {
return self.toString();
});
console.log('hello'.get());
- function converter from "fat arrow" to "function", (inspired by Thomas's answer)
code:
Function.prototype.magicBind2 = function() {
var self = this;
return function() {
return self(this);
}
};
String.prototype.get2 = ((self) => {
return self.toString();
}).magicBind2();
console.log('hello'.get2());
- First solution without explicit use of 'function', which refers to "Function" constructor as (() => {}).constructor to avoid using the word "function" or "Function".
code:
var regex = /\{([.|\s|\S]+)\}/m;
String.prototype.get = (() => {}).constructor(
(() => {
return this;
}).toString().match(regex)[0]
);
console.log('hello, world'.get());
Both solutions so far allow burial of "function" keyword while allowing accessing local scope.