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(),
};
8
  • did you try it? Commented Jul 13, 2018 at 13:49
  • @aquaballin did you mean do I test my "code"? :) Sure, but results is returned with: a.toString and a.function(). I'd like get values with a and a(). Commented Jul 13, 2018 at 13:51
  • 2
    You need to define a function a and then add a toString method to that function. Commented Jul 13, 2018 at 13:57
  • 1
    I am 100% sure that what you are trying to do is not possible, variables in Js can indeed assume different types, but you have to explicitly say that. Commented Jul 13, 2018 at 13:59
  • May be using Proxy? not sure though Commented Jul 13, 2018 at 14:01

1 Answer 1

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());

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

2 Comments

This only works with console.log(String(a)). Logging a alone will log the object.
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.