Basically toString ( ) method is used to convert a number into a String .In this there is no argument .
Syntax
Obj.toString ( )
Simple Example -
var number = 15 ;
var no = num.toString ( ) ; // Output -> 15
Every Object has a toString ( ) method which is automatically called when the object is represented as a text value . And this method is inherited by every Object . If you do not override this method by your method (custom method) then it return ' [ Object type ]' .
Example ->
var obj = new Object ( ) ;
obj.toString ( ) ; // Output : [ Object Object ] ....because you did not override by you custom method
How to override the this method ( toString ) .
Example ->
function student ( name , age , id , sex ) {
this.name = name ;
this.age = age ;
this.id = id ;
this.sex = sex ;
}
stu = new student ( ' Mukesh ' , ' 23 ' , ' 1 ' , ' Male ' ) ;
If you call toString ( ) method in this custom object , then it return the default value which is inherited from Object . i. e
stu.toString ( ) ; // Output : [ Object Object ]
If you want to override this method then you can do by making function ,see below
student.prototype.toString = function studentToString ( ) {
var information = ' student ' + this.name + ' age is ' + this.age + ' and id is ' + this.id + ' and gender is ' + this.sex ;
return information ; // Output : Mukesh age is 23 and id is 1 and gender is Male
Another use of toString ( ) -> Using toString ( ) to detect object class
Example >
var str = Object.toString ;
str.call ( new Date ) ; // Output - [ Object Date ]
str.call ( new String ) ; // output - [ Object String ]
0 Comment(s)