Heretic86 Posted April 27, 2021 Share Posted April 27, 2021 Im messing around with Classes, Inheritance, and some other stuff but to keep it "simple" I'll just say ES6 Classes On one page, I create an instance of a class class MyClass { constructor(name = "", value = ""){ this.name = name; this.value = value; } } const foo = new MyClass("Tom", "123"); There is a lot of other stuff going on, so in order to visually organize the data for the user (there is a LOT), I use a separate page to modify one aspect of the data that they can change. The sub page then uses postMessage to send an instance of the class that is created on the subpage back to the main page, but it loses its Class Type. let msg = { pageMsg : { myData: foo } }; mainPage.postMessage(msg); console.log(msg.data.myMsg instanceof MyClass); // This always returns true on this page Then I process the message back on the main page: // Main Page function messageListener(msg){ console.log(msg.data.myMsg instanceof MyClass); // This always returns false } I left out all the security and module stuff to keep it easy. Is there a way to send a message object from one page to another and retain the Class Instance? Quote Link to comment Share on other sites More sharing options...
waechtertroll Posted September 27, 2021 Share Posted September 27, 2021 The short answer is "no". To pass data through JS message channels, it needs to be serialised by the sender, then deserialised by the receiver. This works for data only, you will lose all function-fields/methods of the class object (a "class constructor" among those methods). As a rule of thumb, if you `JSON.parse(JSON.stringify(data))`, you will see what will arrive on the other hand. In your case you might want to separate the data from the program and send the data only. Maybe add some `{ type: 'im-type-a' }' field, if you need to dispatch on the result type. Somewhat related, if you import an external package, create an instance of a class (sorry, I'm rusty on OOP vocabulary) provided by that package, the use one of the package's helpers that does an `instanceof` check, the check will be `false`, apart from all the ways to monkey-wrench with class instances. You should not trust `instanceof` checks, except maybe against JS' built-in classes (although that can be problematic, too). Quote Link to comment Share on other sites More sharing options...
Jammy Posted September 30, 2021 Share Posted September 30, 2021 Hi, I use workers with postMessage. All my objects just declare their class in the constructor constructor() { this.class = 'SomeClass' } I then use this to make decisions. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.