最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

overriding const function declaration as key in javascript - Stack Overflow

programmeradmin1浏览0评论

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 with n.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
Add a ment  | 

2 Answers 2

Reset to default 4

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();

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.

发布评论

评论列表(0)

  1. 暂无评论