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
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
Share Improve this question asked Aug 28, 2018 at 19:07 NatdripNatdrip 1,1831 gold badge14 silver badges26 bronze badges 3-
5
why do you use
const
for changing content? btw, the above works, but need to call withn.function();
. – Nina Scholz Commented Aug 28, 2018 at 19:08 -
The 'proposed' code shown is "equivalent" to, eg.
const n = {}; n.some_property = some_value
..const
says nothing about the mutability of the named object; just that the name ("n") always evaluate to the same object/value (and thus always 'reflects' the changes to the named object) .. – user2864740 Commented Aug 28, 2018 at 19:18 -
Why doesn't it work? You need to call it as
n.function()
, of course. – Barmar Commented Aug 28, 2018 at 19:28
2 Answers
Reset to default 4You 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();
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 ments.