Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override or Extend the closure function in JavaScript

Just wondering about overriding the closure functions behavior.

e.g. How can i override the baz() function in below snippet?

(function() {
  var foo = 'Hello';
  var bar = 'World!'

  function baz(){
    return foo + ' ' + bar;
  }
})();
like image 484
Imran Avatar asked Mar 17 '26 02:03

Imran


1 Answers

If you are outside the closure, you cannot override the baz() function that is inside the closure. Closures provide privacy and that works for local functions like it works for local variables.

If you are inside the closure, you can define a new version of baz() inside the closure or edit the code inside of baz().

Related question: Can I "extend" a closure-defined "class" in Javascript?

like image 61
jfriend00 Avatar answered Mar 18 '26 16:03

jfriend00



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!