-2

I have a TestComplete (UI testing) project which uses JavaScript, and I'm trying to store class references in JSON. It seems that my code isn't working, so I might have a conceptual misunderstanding of how JavaScript handles class references in JSON. Here's code which demonstrates my line of thinking:

class MyClass {
  constructor() {
    this.name = "ClassName";
  }
}

function print_name(str_name) {
  console.log(str_name);
}

let my_json = {
    "keyOne": [
        MyClass
    ]
};

let class_ref = my_json["keyOne"][0];
print_name(class_ref.name);

Is there a reason why the print_name function would fail to print the "name" property of the MyClass object?

Automatic Bazooty
  • 502
  • 2
  • 6
  • 13

1 Answers1

1

Short Answer : Yes there is a reason for that and the correct code should like this

let my_json = {
"keyOne": [
    new MyClass()
    ]
};

why ?

because you should store an instance of the class not the class itself and to do that in Javascript we use the new key word followed by the constructor function

BTW if you check this code

typeof MyClass

in the console you will get function but its a new syntax comes with the ES2015 a new version of Javascript that make working with a lot of things easier and your code is the same as

function MyClass(){
this.name = "ClassName";
}

so this acts as a blueprint and to create an object you should use the new key word followed by the constructor like this

let mySimpleClass = new MyClass();

now if you console

mySimpleClass.name you will git ClassName

note:- if you want to convert your my_json variable to actual Json use this

JSON.stringify(my_json);

learn more :

Working with Javascript Objects

JSON.stringify()

mostafa tourad
  • 4,308
  • 1
  • 12
  • 21