1

When creating a x = new Date() object, if you put it into console.log(x) a string will be output.

Is there a way to make a custom object that will return a different value that is not an object itself

Jason
  • 779
  • 1
  • 9
  • 30
  • Not while using the `new` keyword. By definition, it will return an instance of the function you invoke. However, you can say something like `x = new MyObj().init()` and you can define an init function on your object that returns something other than the object itself. – mhodges Jan 19 '17 at 18:11
  • 2
    Define the function `toString()` in your new object. – some Jan 19 '17 at 18:12
  • or use JSON.stringify like [here](http://stackoverflow.com/questions/5612787/converting-an-object-to-a-string) it even works with date-objects as well – Blauharley Jan 19 '17 at 18:14
  • @blauharley, mhodges i dont get the part that relates to the question. – Jonas Wilms Jan 19 '17 at 18:15
  • @Jonasw I thought the OP wanted x to equal something that was not the object itself when saying `x = new Date()`. In all fairness, the question states "to make a custom object return a different value" and the title of the question states "get an object to return a value". The object is not returning a value when `console.log()` is called, the `toString()` function is returning a value. Technically my comment answers the actual question as it's worded, but I may have misunderstood the intent of the question. – mhodges Jan 19 '17 at 18:34

4 Answers4

2

There is a function for that, toString, however if you just do console.log(new Test) it will still output the object. But if your force it so print a string it will work: console.log('%s', new Test):

function Test() {
}

Test.prototype.toString =
  function () {
    return "Something else";
  }


console.log("%s", new Test);

> Something else

Or if you concatenate it with another string:

var a = new Test;
console.log('Result: ' + a);

> Result: Something else

I use this a lot in my code to display a summary of the content of a object with data.

There is also valueOf:

Test.prototype.valueOf =
  function () {
    return 42;
  }

console.log("%d", new Test);

> 3
some
  • 48,070
  • 14
  • 77
  • 93
1

Basically two methods returns values, which are not the object itself.

Object#toString

Every object has a toString() method that is automatically called when the object is to be represented as a text value or when an object is referred to in a manner in which a string is expected. By default, the toString() method is inherited by every object descended from Object. If this method is not overridden in a custom object, `toString() returns "[object type]", where type is the object type.

Object#valueOf

JavaScript calls the valueOf method to convert an object to a primitive value. You rarely need to invoke the valueOf method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected.

By default, the valueOf method is inherited by every object descended from Object. Every built-in core object overrides this method to return an appropriate value. If an object has no primitive value, valueOf returns the object itself.

You can use valueOf within your own code to convert a built-in object into a primitive value. When you create a custom object, you can override Object.prototype.valueOf() to call a custom method instead of the default Object method.

To break it down for your question, you can implement both methods to a custom function.

When both methods are implemented and return primitive values, the valueOf is called first. If valueOf returns an object, toString method is called.

You might have a look to this article: Fake operator overloading in JavaScript

function Custom(value) {
    this.value = value;
}

Custom.prototype.valueOf = function () {
    console.log('valueOf');
    return this.value * 5;
};


var custom = new Custom(7);

console.log('' + custom); // no toString

Custom.prototype.toString = function () {
    console.log('toString');
    return this.value * 3;
};

Custom.prototype.valueOf = function () {
    console.log('valueOf');
    return {};
};

console.log('' + custom);
Community
  • 1
  • 1
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

Overwrite toString of an Object:

My comment above refered to toString as well. You can use JSON.stringify to print out all properties of an object on the fly within an object's toString method:

function MyObject() {
  this.a = 'a';
  this.b = 'b';
  this.c = 'c';
}

MyObject.prototype.toString = function () {
  return JSON.stringify(this);
};

console.log((new MyObject()).toString()); // {"a":"a","b":"b","c":"c"}
// or
console.log('new MyObject(): ' + new MyObject()); // new MyObject(): {"a":"a","b":"b","c":"c"}

Overwrite console.log:

Another try might be to overwrite console.log to print always strings (only tested in FF!):

// initialize this only once so that console.log prints out correctly

(function () {
  var oldConsole = console.log;
  console.log = function (obj) {
    oldConsole(JSON.stringify(obj));
  };
}) ();

// now console.log prints strings
console.log({
  a: 'a'
}); // String: {"a":"a"}

console.log(new Date()); // String: "2017-01-19T19:09:49.673Z"

console.log(document); // String: {"location":{"href":"http://stackoverflow.com/questions/41748793/javascript-how-to-get-an-object-to-return-a-value-that-is-not-the-object-itsel/41749121#41749121","origin":"http://stackoverflow.com","protocol":"http:","host":"stackoverflow.com","hostname":"stackoverflow.com","port":"","pathname":"/questions/41748793/javascript-how-to-get-an-object-to-return-a-value-that-is-not-the-object-itsel/41749121","search":"","hash":"#41749121"},"jQuery112409140067213472354":3}
Blauharley
  • 4,186
  • 6
  • 28
  • 47
-1

You can convert most of the objects to string as follows

String(object)

like

x = String(new Date()); // now x is a string 

Similarly

x = Boolean(0); // wil return an object
x = String(Boolean(0)); // will return a string
Mitesh Pant
  • 524
  • 2
  • 15