JavaScript property aliases

So, I have a property for which I want to make an alias.

var default_commands = {} default_commands['foo'] = "bar"; 

Then I want a bunch of items with the alias "foo"

So, if I wanted to

 default_commands['fu'] = default_commands['foo']; default_commands['fuu'] = default_commands['foo']; 

How can I do this, so I don’t need to write everything

I tried:

 default_commands['fu','fuu'] = default_commands['foo']; 

But that did not work.

+4
source share
5 answers
 ["fu", "fuu"].forEach(function (alias) { default_commands[alias] = default_commands.foo; }); 

This will not be a "pseudonym" in the sense that the word usually invokes:

 default_commands.fu = 5; console.log(default_commands.foo); // still "bar", not 5. 

But it was not clear what you had in mind in your question.

+4
source

You can do it

 default_commands['fu'] = default_commands['fuu'] = default_commands['foo']; 
0
source

The solution is perhaps the most flexible:

 function unalias (str) { // Use whatever logic you want to unalias the string. // One possible solution: var aliases = { "fu": "foo", "fuu": "foo" }; return aliases[str] !== undefined ? aliases[str] : str; } default_commands[unalias("fu")] = 7; default_commands[unalias("fuu")] = default_commands[unalias("foo")] + 3; alert(default_commands.foo); 

Why is it more flexible? Reading and writing will be "properly distributed."

0
source

The only way you can really use aliases in javascript is to use objects.

Objects are available in js, for example pointers:

Example:

 var myobj = {hello: "world"}; var myalias = myobj; myobj.hello = "goodbye"; console.log(myobj.hello); => // "goodbye" console.log(myalias.hello); => // "goodbye" 

You cannot create an alias for string, number, boolean, etc.

Example:

 var myint = 1; var myalias = myint; myint = 2; console.log(myint); => // 2 console.log(myalias); => // 1 

PD: all types (e.g. Array or RegExp) except Int, String, Boolean, null and undefined are treated as objects.

0
source

You already thought about it.

 var foo="foo",fu=foo,fuu=foo,default_commands = {}; default_commands[foo] = "bar"; console.log(default_commands[foo]); default_commands[fu] = "baz"; console.log(default_commands[foo]); default_commands[fuu] = "bing"; console.log(default_commands[foo]); 
0
source

Source: https://habr.com/ru/post/1385259/


All Articles