0
function test() {
    alert(1);
    return "hello";
}

Function.prototype.before = function (func) {
    var __bself = this;
    return function () {
        if (func.apply(this, arguments) == false)
            return false;

        return __bself.apply(__bself, arguments);
    }
};

test.before(function (){
    alert(2);
})();

What is the meaning of if (func.apply(this, arguments) == false)? I don't think the function will return false.

Peter Seliger
  • 11,747
  • 3
  • 28
  • 37
  • 5
    This *particular* function won't return false, but others may... – ssube Jun 07 '16 at 19:00
  • Regarding the former `AOP` tag, wrapping and reassigning already declared functionality (be it functions or methods) misses any aspect of _AOP_. Any language which wants to qualify for the latter has to provide abstraction levels for at least `Joinpoint`, `Advice` and `Aspect`. The use case described by the OP should be referred to as method modification, and JavaScript of cause is well suited for this scenario and could easily provide a complete `target`/`context` aware toolset of method modifiers like `around`, `before`, `after`, `afterThrowing` and `afterFinally` via `Function.prototype`. – Peter Seliger Sep 14 '22 at 17:16

1 Answers1

2

Functions can return any value. That includes false.

If your functions don't return false then the code inside that conditional will never run. So you can remove it, if it annoys you for some reason.

Here is an example with a function which returns false:

function test() { // This function is never called
  console.log(1);
  return "hello";
}
Function.prototype.before = function (func) {
  var __bself = this;
  return function () {
    if (func.apply(this, arguments) == false){
      return false;
    }
    return __bself.apply(__bself, arguments);
  }
};
test.before(function (){
  console.log(2);
  return false;
})();
Oriol
  • 274,082
  • 63
  • 437
  • 513