Javascript 从对象'规范化下划线;在将获取程序发送到API之前,请先获取它们
我想保存一个使用getter和setter的JS对象,使用:Javascript 从对象'规范化下划线;在将获取程序发送到API之前,请先获取它们,javascript,Javascript,我想保存一个使用getter和setter的JS对象,使用: export default class Item { get id () { return this._id; } set id (value) { this._id = value; } get name () { return this._name; } set name (value) { this._
export default class Item {
get id () {
return this._id;
}
set id (value) {
this._id = value;
}
get name () {
return this._name;
}
set name (value) {
this._name = value;
}
constructor (id, name, children) {
this._id = id;
this._name = name;
this._children = children;
}
test () {
// ...
}
}
new Item(item.id, item.name, item.children)
我需要JavaScript getter和setter,因为我必须处理再次调用自身的嵌套项
这可以通过以下方式轻松完成:
get children () {
return this._children.map((child)=>{
return new Item(child.id, child.name)
});
}
我正在处理这个对象,有一点我想通过调用PHP-API来保存它:
async save () {
let method = 'put';
let url = '/api/item';
let data = {item: this.item};
axios ({method, url, data}).then ((response) => {
// ...
})
},
现在PHP-API接收到一个对象,其属性以\uu
开头(比如:\u id
),这在某些点上破坏了PHP逻辑
我的问题:是否可以调用所有getter来获取包含
名称
和id
道具的对象,而不是\u名称
和\u id
?我的第一个问题是:为什么需要javascript上的getter和setter?我觉得您正在尝试像java一样使用javascript。只需使用一个名为id
的读/写属性。我看不出在您的代码中使用get id(){返回这个。_id;
。etcI添加了一个示例,说明为什么我需要处理getter和setter。您可以重写类toString
函数