0

Let assume we have object like this:

let person = {name: 'Ken', doSometing: ()=>{}, data:{}}

or this:

let Person = function(name) {
    this.name = name;
    this.data = {};
    this.doSometing = ()=>{};
};
let person = new Person('Ken');

And i was intresting, is there a way to make objects like this, but get name propery when calling object by itself (name can be string, number, object and so on):

console.log(person) //Ken

instead:

console.log(person.name) //Ken
ZiiMakc
  • 31,187
  • 24
  • 65
  • 105
  • 1
    Possible duplicate of [valueOf() vs. toString() in Javascript](https://stackoverflow.com/questions/2485632/valueof-vs-tostring-in-javascript) – VLAZ May 14 '19 at 19:48
  • There's not much you can do about `console.log`. `console.log` is a debugging tool, so it tends to display the object as is, even if you override `valueOf` or `toString`. – melpomene May 14 '19 at 19:50
  • 1
    The comment from @melpomene suddenly reminded me that I answered a similar question a few years ago and invented a rather troubling mechanic: https://stackoverflow.com/a/43416818/710446. Follow my advice there at your own peril. – apsillers May 14 '19 at 19:59

1 Answers1

1

The mechanical problem with this design is that primitives (like strings, numbers, and booleans) cannot have their own properties. You could add a property to the primitive's associated prototype, like String.prototype.doSomething = function() { ... }, which would allow you to do "foo".doSomething(). (This is discouraged, though, since you should not modify objects you don't own.) However, you cannot attach a value to a specific primitive string value, which means you cannot implement data and name how you'd like.

Instead, the best option is likely to use an object with a toString method that will allow you to stringify the object to a string of your desired form. This won't show in console.log form, but it would if you added an empty string to it, like console.log(""+person).

If you want to give nightmares to anyone who maintains your code in the future, you could achieve this by having your object include RegExp.prototype in its prototype chain. I strongly, actively discourage you from doing so, but suppose I'm not legally capable of stopping you, either; whether or not it should be, (ab)using RegExp.prototype in this way is not (yet) a crime in any jurisdiction.

apsillers
  • 112,806
  • 17
  • 235
  • 239