javascript - Are JS imports immutable or non-writable? - Stack Overflow

From what I can tell, an import binding is immutableimport { foo } from '.foo';...foo.bar

From what I can tell, an import binding is immutable

import { foo } from './foo';
...
foo.bar = 23; // works 
...
foo = { bar: 23 }; // syntax error

However, I've read elsewhere that JS imports are actually non-writable (not immutable)...in which case wouldn't the first assignment statement, foo.bar = 23; also throw a syntax error?

UPDATE (how I understand it now)

...to paraphrase the excellent answer by @FelixKing...

JS imports are immutable bindings to the exported thing (variable, function, etc).

For non-primitive imports, this does not mean the properties on the imported object are necessarily immutable or non-writable.

From what I can tell, an import binding is immutable

import { foo } from './foo';
...
foo.bar = 23; // works 
...
foo = { bar: 23 }; // syntax error

However, I've read elsewhere that JS imports are actually non-writable (not immutable)...in which case wouldn't the first assignment statement, foo.bar = 23; also throw a syntax error?

UPDATE (how I understand it now)

...to paraphrase the excellent answer by @FelixKing...

JS imports are immutable bindings to the exported thing (variable, function, etc).

For non-primitive imports, this does not mean the properties on the imported object are necessarily immutable or non-writable.

Share Improve this question edited May 23, 2017 at 10:31 CommunityBot 11 silver badge asked Mar 29, 2017 at 13:45 sfletchesfletche 49.8k31 gold badges109 silver badges120 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9

in which case wouldn't the first assignment statement, foo.bar = 23; also throw a syntax error?

Non-writable refers to the value of the variable, where as mutable (immutable) describes whether the value itself can be changed in place or not.

Imports are not writable as you have found out. But if the value of an import is mutable then you can update the value (in place).

foo.bar = 23;

does not assign a new value to foo. It is reading the value of foo and then modifying it (by adding or overwriting a property). If you did

var oldFoo = foo;
foo.bar = 23;
oldFoo === foo; // true

you would get true. That indicates that foo has still the same value assigned to it. It only updated the value (an object) in place.

All objects are mutable (unless passed to Object.freeze or similar functions), whereas primitive values (String, Number, etc) are all immutable.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744302140a4567551.html

相关推荐

  • javascript - Are JS imports immutable or non-writable? - Stack Overflow

    From what I can tell, an import binding is immutableimport { foo } from '.foo';...foo.bar

    7天前
    60

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信