`this()` to call a function from itself

Currently, calling this() returns an error as this is not declared. That means that this feature will not conflict with any JS use of this. This will allow to call itself in a function or an arrow function. Examples:

// Factorial Function:
function factorial(n) {
    return (n == 0) ? 1 : (this(n-1) * n)
}

// Factorial Lambda:
n => (n == 0) ? 1 : (this(n-1) * n)

// Fibonacci Lambda:
n => (n < 2) ? 1 : (this(n-1) * this(n-2))

// Is number a prime? Lambda:
n => {
    for (let i = 2; i < Math.sqrt(n); i++)
        if (n%i == 0) return false
    return true
}

// Quick for loop from zero to hundred:
((n) => {
    if (n > 0) this(n-1)

    // Run code here that should be repeated 101 times, with n = 0 .. 100
})(100)

The use of a quick way to call the function you're in allows for so many expressive ways to write problems. Hoping this to be reviewed!

this() will work if this is a function.

function foo () {
    console.log('foo called')
}

function callThis () {
    this()
}

callThis.call(foo) // "foo called"
3 Likes

And building on that we can achieve this today by using a helper utility.

// const bindSelf = f => f.bind(f);
// EDIT:
const bindSelf = f => {
   return function f2(...args) {
      return Reflect.apply(f, f2, args);
   };
};

const factorial = bindSelf(function (n) {
    return (n == 0) ? 1 : (this(n-1) * n);
});
factorial(6) // 720

Though I would still personally stick to:

function factorial(n) {
    return (n == 0) ? 1 : (factorial(n-1) * n);
}
2 Likes

Or just do let bindSelf = f => f.bind(f).

That won't work recursively. The first call to this will be to the unbound version.
(I made the same mistake the first time I tried to implement it)

1 Like

Good point. :confused: