Question

I was simply practicing a little bit of JavaScript. My goal was to create a function that can call another function with the .invoke() until .revoke() is called, which then nullifies the function.

Later on, I've added .porcupine() which was, in theory, supposed to take the firstly invoked function (in this case, alert()) and then reapply it to the original "temp". The issue is, though, after being revoked temp becomes unknown, therefore it can not call anything anymore. Is there something very obvious to this that I'm missing out or will the solution have to be fairly messy?

var denullifier;

function revocable(unary) {
 if (denullifier === null)
    denullifier = unary;

return {

    invoke: function(x) {
           return unary(x);
    },

    revoke: function() {
           var nullifier = unary;  
           unary = null;
           return nullifier.apply(this, arguments);       
    },

    porcupine: function() {
           unary = denullifier;
               return unary.apply(denullifier, arguments);
        }
    };
};

    console.log('----------');
    temp = revocable(alert);
temp.invoke(7); ///alerts 7
temp.revoke();
temp.porcupine(); //exception
temp.invoke(7); //doesn't get here
Was it helpful?

Solution 2

This is your problem:

var denullifier;

function revocable(unary) {
  if (denullifier === null)
    denullifier = unary;

denullifier is undefined when declared without a value. However, you are checking for type-strict equality with null, which will be false, so denullifier is never set and porcupine is not able to restore the unary function.

I'd suggest:

  • Use == instead of === to get equality with undefined
  • Even better, use typeof denullifier != "function"
  • Or, (although I don't know your design) you should not make denullifier a global, static variable that will be shared amongst revocable instances, but instead make it instance-specific by putting the declaration inside the function body.

OTHER TIPS

I don't quite understand what you're doing, but there are a few problems with your code.

 if (denullifier === null)
    denullifier = unary;

denullifier is not null here, it's undefined - so the condition isn't met.

    return nullifier.apply(this, arguments);       

You can't call alert this way, the first param must be null or window.

    return unary.apply(denullifier, arguments);

The same.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top