简体   繁体   English

即使原型方法中正确,JavaScript原型返回值也未定义

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

I'm trying to create a simple method to convert xml to json. 我正在尝试创建一个简单的方法来将xml转换为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(); 我正在尝试使用javascript的原型来完成此任务,因为我正在尝试学习如何使用原型,并且因为我希望能够执行myXmlString.toJson();类的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. 我有下面的脚本,该脚本演示xml字符串在方法内部可以很好地转换为json对象,但是当我尝试调用该方法时,它是未定义的。

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) {
      console.log('err');
      console.log(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?

Inside your toJson method, you should return the value parseString returns. 在toJson方法中,您应该返回parseString返回的值。 At the moment, you just execute parseString without returning the value it returns. 此刻,您只执行parseString而不返回它返回的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM