How to create a revocable function to grant/revoke access to any other function?

The following code will show you how to create a function ‘revocable’ that will be used to grant/revoke access to other functions.

The function that will be tested here is the add function to add 2 numbers. But the ‘revocable’ function is good enough to work for other functions as well.

function add (x, y) {
    return x + y;

Given below is the code for the ‘revocable’ function:

function revocable(fn) {
    var allow = true;
    return {
        invoke: function() {
            if(!allow) {
                throw new Error('Access revoked');
            return fn.apply(this, arguments);
        revoke: function() {
            allow = false;
        grant: function() {
            allow = true;

var temp = revocable(add);

temp.invoke(3, 4); // 7


temp.invoke(3, 4); // Uncaught Error: Access revoked(…)


temp.invoke(3, 4); // 7