5

Is it possible to create variable/object, which returns string and function at the same time?

> a
'Hello World'
> a()
2018-07-13T13:45:10.967Z

I've seen article about default methods of JavaScript objects, but I couldn't find it now.

I think it should be something like:

// Pseudo code
const a = {
    toString: "Hello World",
    function: () => new Date(),
};
Mateusz Jagiełło
  • 6,854
  • 12
  • 40
  • 46

1 Answers1

1

AFAIU this is only possible if, when you need the string, you use the variable in a way to enable explicit or implicit conversion, like this:

const a = function () {
  return new Date()
};
a.toString = function() {
  return "Hello world";
}

console.log('' + a);
console.log(String(a));
console.log(a());
Nelson Teixeira
  • 6,297
  • 5
  • 36
  • 73
  • 1
    This only works with `console.log(String(a))`. Logging `a` alone will log the object. – Bergi Jul 13 '18 at 17:44
  • @bergi thanks for pointing my error. I was led to believe it was ok because in SO's snippet if you run the code the output of `console.log(a)` outputs `Hello World`. As I tried outside of it I saw you were right. I corrected my answer. – Nelson Teixeira Jul 13 '18 at 17:56