Javascript prototype returning value is undefined even though it's correct in the prototype method

Friday, July 11, 2014

I'm trying to create a simple method to convert xml to json. I'm trying to do it using javascript's prototype because i'm trying to learn how to use prototype and because I want to be able to do something like myXmlString.toJson();

I have the script below which demonstrates that the xml string gets converted to a json object just fine inside the method, but when i try to call the method it is undefined.

var parseString = require('xml2js').parseString; // Used to parse the returned xml (ick) to json (yum)

String.prototype.toJson = function() {
parseString(this, {explicitArray: false}, function (err, jsonResult) {

if(err) {
return err;

console.log('inside toJSON');
console.log(jsonResult); // <-- Prints a json object as expected

return jsonResult;

var mystring = '<parent><child>3</child></parent>';
console.log(mystring); // Prints an xml string

mystring.toJson(); // Should this convert the variable mystring to a json structure?
console.log(mystring); // Prints the xml string
console.log(mystring.toJson()); // Prints undefined. Why?