Mosijava
Mosijava

Reputation: 4199

how to return string from constructor function in javascript?

as you know when we new a Date object it returns an string,

it means when you execute this code

console.log(new Date());

it returns an string like this: Sun Jan 17 2016 16:26:55 GMT+0330 (Iran Standard Time)

i want to do exact the same thing and return an string when somebody new my object...

is it possible?

Upvotes: 2

Views: 957

Answers (1)

guysigner
guysigner

Reputation: 2922

It is possible. You can to use Object.prototype.toString (reference in this link):

function MyObject () {
  this.numProperty = 1;
  this.strProperty = "some string";
}
MyObject.prototype.toString = function (){
 return this.strProperty;
}

// example usage:
var obj = new MyObject();
document.getElementById("x").innerHTML = obj;

EDIT: for console.log behavior you can use either

console.log(obj.toString());

or

Console.prototype.logO = function (obj) {
    this.log(obj.toString());
}
// and then
console.logO(obj);

The last line is what you wanted in the first place, but I would go for the first option as it's less wordy.

Here's a JSFiddle.

Upvotes: 2

Related Questions