Reputation: 1183
Hi and thank you in advance
I am wondering if there is a way to override a const function?
example:
const n = function(){alert('bob')};
so is it possible to reference the function something like this:
n.function = function(){alert('for apples')};
What I did here doesn't work.
Thanks again
Upvotes: 0
Views: 2366
Reputation: 1377
From the docs
The value of a constant cannot change through re-assignment, and it can't be redeclared.
Since functions are objects though you can add properties to them. Therefore, n.function = function(){alert('for apples')};
will work since you are appending a property called function
to your n
object. That means that you can execute that function by doing n.function()
as Nina Scholz suggested in the comments.
Upvotes: 4
Reputation: 2161
You can't override the value of a const
-declared variable. Just use let
instead.
let n = function() { alert('bob'); };
n();
n = function() { alert('for apples'); };
n();
Upvotes: 4