提问人:theRook 提问时间:11/17/2023 最后编辑:theRook 更新时间:11/17/2023 访问量:17
将类的 JavaScript 实例导出到另一个文件并保留原型和方法
export a javascript instance of a class to another file and retain prototype and methods
问:
我正在努力提高javascript,node和express,并尝试将类的实例从app.js文件提供给另一个js文件,并且仍然能够保留和实现类方法。我正在使用 node.js 和 express。以下是我正在尝试执行的操作的示例:
人.js
export default class Person{
constructor(name){
this.name = name;
}
someMethod(){
this.name = "new name";
}
}
应用.js
import express from "express";
import bodyParser from "body-parser";
import Person from "./public/classes.js";
const myPerson = new Person("John Smith");
//setup Express server here
const app = express();
const port = 3000;
app.use(bodyParser.urlencoded({ extended: true }));
app.listen(port, () => {
console.log(`Listenings on port ${port}`);
});
//provide route to fetch object from
app.get("/getPerson", (req, res) => {
res.send(myPerson);
});
其他文件.js
import Person from "./classes.js";
//fetch the Person object from the app.js
const response = await fetch("/getPerson");
const myPerson = await response.json();
//Try to call a method from the Person class on myPerson
myPerson.someMethod() // this throws an Uncaught TypeError: myPerson.someMethod() is not a function
这是我试图修复的最后一行。我希望能够在myPerson对象上调用类的方法。经过检查,myPerson 对象的原型中似乎不再具有该类最初附加的方法。我做错了什么,有没有更好的方法?
更新:
经过一些实验,我找到了两种在提取的对象上使用 Person 方法的方法。
- 在 myPerson 上使用 .setProtoTypeOf() 方法,如下所示:
myPerson.setProtoTypeOf(Person);
- 创建一个将 json 响应转换为新 Person obj 的方法。
const person = new Person(myPerson.name);
当然,根据传递对象中的字段数量,这会更复杂,但由于 MDN 在使用 .setProtoTypeOf() 时会发出巨大的警告,我认为这是更好的方法。
答: 暂无答案
评论