4

So I have a property I want to make alias's for.

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

Then I want a bunch of items to alias to "foo"

So if I wanted

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

How could I do that so I don't have to write that all out

I tried:

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

But that didn't seem to work.

5 Answers 5

4
["fu", "fuu"].forEach(function (alias) { default_commands[alias] = default_commands.foo; }); 

This won't be an "alias" in the sense that word usually invokes:

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

But it wasn't clear what you meant in your question.

Sign up to request clarification or add additional context in comments.

1 Comment

this looks like it's doing what i want
0

You can do this

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

1 Comment

that's only slightly less painful to write
0

Solution that is probably 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 this more flexible? Read and writes will "propagate" properly.

2 Comments

this seems like it's making it more complicated
@mcgrailm: I drastically changed my solution.
0

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

Objects are accesed in js like pointers:

Example:

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

You cant make an alias for a string, number, boolean, etc..

Example:

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

PD: All types (like Array or RegExp) except Int, String, Boolean, null and undefined are treated like Objects.

Comments

0

You're over thinking 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]); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.