JavaScript: How to stringify a class, after calling new

浪子不回头ぞ 提交于 2019-12-11 08:14:13

问题


TL;DR: I need to inject some JavaScript into a BrowserView in Electron using executeJavaScript. This code needs to be class. How can I stringify the class?

I found out that you can stringify functions using +.

const fn = function() {
  console.log('Hello');
};
const functionToText = '' + fn;
console.log(functionToText);
// function() {
//   console.log('Hello');
// }
*/

But my problem is, how can you stringify classes? I need the string version of the following object created from the class with new to inject it.

class Person {
  constructor({ name }) {
    this.getName = () => name;
  }
}
const person = new Person({ name: 'John'});
const str = // somehow stringify person here
console.log(str);
// the person object
view.webContents.executeJavaScript(`window.person = ${str}`);

Edit:

Here is how I ended up implementing it based on the accepted answer:

view.webContents.executeJavaScript(
  `window.person = new ${str}({ name: 'John' })`
);

回答1:


You had the solution in your question. The same approach that works for functions works for classes too.

class Person {
  constructor({ name }) {
    this.getName = () => name;
  }
}
const str = '' + Person;
console.log(str);

Updated in response to additional data in question. You can't serialize an object and make it cross execution boundaries because it is no longer data at that point, but instead is running in memory.

One approach you could take is invoke all of the code inside the call to executeJavaScript

For example:

view.webContents.executeJavaScript(`
class Person {
  constructor({ name }) {
    this.getName = () => name;
  }
}

window.person = new Person({name: 'John'});
`);

Or alternatively

view.webContents.executeJavaScript(`
(function() {
    class Person {
      constructor({ name }) {
        this.getName = () => name;
      }
    }

    window.person = new Person({name: 'John'});
})();
`);


来源:https://stackoverflow.com/questions/58000056/javascript-how-to-stringify-a-class-after-calling-new

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!