2

I want to output new Date().getDate()

But getDate() is inside a string

fn = "getDate()"
d = new Date();


// How do I make it work?
console.log(d.fn);

The problem is that I can't use it as it is now.

You can test it on: http://jsfiddle.net/99tayr5b/

Many thanks!

Tudor
  • 319
  • 5
  • 13

2 Answers2

2

You can put the method name getDate without () into a string and use bracket notation:

fn = "getDate"
d = new Date();

console.log(d[fn]());

Demo: http://jsfiddle.net/99tayr5b/1/

tymeJV
  • 103,943
  • 14
  • 161
  • 157
1

console.log(new Function('obj', 'return obj.' + fn)(d)); works.
But it's dirty solution and I can't recommend it.

Pavel Birukov
  • 308
  • 1
  • 8