0

I was experimenting with some javascript when I came across a syntax error. I was trying to assign an object key with a value that is returned from a method.

var a = new function(){
    this.b = function()
    {
        return "c";
    }
};


var myobj = {
   a.b:"d" //Syntax error, unexpected '.'
};

The above will throw an error; but then javascript will allow:

var n = a.b;

var myobj = {
   n:"d" //no error
};

Even though typeof a.b and typeof n returns both the same as function?

James A
  • 467
  • 4
  • 12
  • `myobj.n` will return "d". Starting with es6, you can put the variables in `[]` to use a variable as an object key. Though I don't think that that is what you want in this case. – baao Sep 05 '16 at 14:25
  • 2
    The `n` in `n:"d"` is the property with the name `n` and is not related in any way to the `n` of `var n = a.b;`. – t.niese Sep 05 '16 at 14:26
  • Why would you ever want a method to become a key? Or do you mean the name of a method as a key? – Shilly Sep 05 '16 at 14:27
  • The return value of a.b is meant to become the name of the key – James A Sep 05 '16 at 14:28
  • `var myObj = {}; myObj[a.b()] = "d";` I still can't think of a use case for this unless you're building like self modifying code. :) – Shilly Sep 05 '16 at 14:29
  • 3
    [Related](http://stackoverflow.com/questions/2274242/using-a-variable-for-a-key-in-a-javascript-object-literal), maybe dupe? Same answer really, but question asked is a bit different. – James Thorpe Sep 05 '16 at 14:30

2 Answers2

2

Though it seems very strange, but I expect you want to get a result if you log myobj.c. With es6 you can do the following:

var a = function(){
    this.b = function()
    {
        return "c";
    }
};


var myobj = {
   [a.b()]:"d" 
};

console.log(myobj.c); // d

But why would you ever want to do this?

baao
  • 71,625
  • 17
  • 143
  • 203
1

I guess you're trying something like this?

var myobj = {
   "d": a.b
};

and then myobj.d() or @baao has already answered the other possibility?

Hassan
  • 930
  • 3
  • 16
  • 35