Objects Convert Using Js Tostring() Method Gives Odd Result?
code in the below shown results of few conversions of data types using toString() method. all other data types can convert to strings using toString() method but when try to conver
Solution 1:
In Javascript all objects inherit from Object. For a custom object if you don't define the toString() method it will inherit it from its parent class. So obj.toString() prints "[object Object]" because it is an object (a primitive type) of type Object.
Solution 2:
Javascript has several built-in Objects,
Eg:
- JavaScript Number Object
- JavaScript Boolean Object
- JavaScript String Object
- JavaScript Array Object
- JavaScript Date Object
- JavaScript Math Object
- JavaScript RegExp Object
Each Object has the toString
method implemented in different ways.
For user-defined objects the default toString method returns [object Object]
. You can override it if you want..
functionCar(type){
this.type = type;
}
Car.prototype.toString = function(){
returnthis.type + " car";
}
var car = newCar('bmw');
alert(car.toString());// produce "bmw car"
Also you can even rewrite Object.prototype.toString
method (but may be not a good idea).
Object.prototype.toString = function() {
returnJSON.stringify(this); ;
}
var obj = { name: 'John' }
alert(obj.toString());// produce "{ "name": "John"}"
Post a Comment for "Objects Convert Using Js Tostring() Method Gives Odd Result?"