-2

I have strange but interesting question and I will start right from examples.

Imagine I have an object which looks like that:

const stringEvaluate = {
    toString: () => 'Im object'
}

Now I can create string using this object

stringEvaluate + ' stringified'

// Im object stringified

And also I can do something like that:

const numberEvaluate = {
    valueOf: () => 1337
}

And turn this object into:

numberEvaluate + 682

// 2019

My questions is: Can I override some object property which will help me to do something like that:

const evaluatedObject = {
   someProperty: () => 'I was object, but not now'
}

const magic = evaluatedObject

console.log(magic)
//'I was object, but not now'
Puwka
  • 640
  • 5
  • 13
  • 1
    It is not exaclty clear what do you want to override. Return values or whole methods? – Eriks Klotins Aug 14 '19 at 16:54
  • I mean object should not return itself with a properties when I call it, but it will return other type of data. In my example `magic` will be equal `{someProperty: ƒ}` I want it to be equal `'I was object, but not now'` – Puwka Aug 14 '19 at 16:57
  • Can't you just set `magic` to the result of the function: `const magic = evaluatedObject.someProperty()` ...? Or if you were looking for something "cheeky", override `.toString()` like in your first example, and do `const magic = \`${evaluatedObject}\`` or `const magic = evaluatedObject+""` – Tyler Roper Aug 14 '19 at 16:58
  • Yeah, it should be "cheecky". I want to call it without any modifiers like template literals, etc. Just with assignment. `const magic = evaluatedObject` – Puwka Aug 14 '19 at 17:00
  • Related: [Is it possible to override JavaScript's toString() function to provide meaningful output for debugging?](https://stackoverflow.com/questions/6307514/is-it-possible-to-override-javascripts-tostring-function-to-provide-meaningfu) **and** [Does console.log invokes toString method of an object?](https://stackoverflow.com/questions/36215379/does-console-log-invokes-tostring-method-of-an-object) – Tyler Roper Aug 14 '19 at 17:07
  • You might be able to do something with a [Proxy](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) – Get Off My Lawn Aug 14 '19 at 17:17

1 Answers1

1

The way the console shows objects is not specified. However it would be a really bad behaviour if the console would cause side effects when logging, or in other words: if it would call an object's method when executed. So no, what you want to do is not possible, also I don't see any usecase for that.

If you want to enrich the debugging experience, you can still add your own logger:

 const log = (...args) => {
   console.log(`It is ${new Date}`, ...args);
 };
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151