2

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?

5
  • what do you mean by 'somebody new my object'? Commented Jan 17, 2016 at 13:03
  • So you have a constructor, and want to convert the instances to strings? Commented Jan 17, 2016 at 13:07
  • @TarunDugar excuse me for my bad English ,,, I mean if my object is Date2 then I want to return an string when someone call new Date2() Commented Jan 17, 2016 at 13:23
  • you cannot do new Date2(). If you want to convert something to string use toString() Commented Jan 17, 2016 at 13:24
  • 1
    new Date() does not return a string. It's just the console that formats Date objects as such. Commented May 11, 2016 at 6:00

1 Answer 1

2

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.

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

1 Comment

thanks for answer but as you can see in your fiddle, it works with innnerHTML() function but it's not working with console.log(). is there any way to makes it work in console.log?

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.