0

I want to print data of an object in JavaScript. By defining a function and calling that function, i'm able to do that. To call such function i'm using s.show() in my code. But what i want is... by just specifying s [ like document.write(s) ], i want to print the object. In Java language, when we try to print an object, the System.out.println() calls the toString() method on that object. Is there any way in JavaScript?

Please help. Thanks in Advance.

<script>
function stud(a,b,c)
{
  this.one=a;
  this.two=b;
  this.three=c;
  this.show=function toString()
    {
        document.write(a+","+b+","+c+"<br>");
    }
}
var s=new stud("smile","laugh","cry");
s.show(); // this is working
document.write(s); // i want this also work same
</script>
3
  • 1
    if you need this just for logging purposes, consider console.log(s). Commented Jan 23, 2014 at 10:46
  • document.write(JSON.stringify(s)); Commented Jan 23, 2014 at 10:49
  • JSON.stringify() is displaying the object's properties and values but i want only the values to be printed. any help? Commented Jan 25, 2014 at 10:47

1 Answer 1

1

You can print any Javascript Object by using its logging functions.

There are basic 3 functions for loging

console.log( s ); // You can use this one.

Or you can parse your object like this also.

function stud(a,b,c)
{
  this.one=a;
  this.two=b;
  this.three=c;
  this.show=function toString()
  {
     // This will print your json as string as print in JAVA.
     document.write( JSON.stringify(this) );
  }
}

Input:

var s=new stud("smile","laugh","cry");
s.show(); // this is working

Output:

{"one":"smile","two":"laugh","three":"cry"}
Sign up to request clarification or add additional context in comments.

1 Comment

the JSON.stringify() is displaying both properties and values of the object. But I want only the values of the object. I mean, the toString() of my code should be called when i try to display the object (using 'docuement.write(s)') to the user.

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.