在 JS 中,特别是对于 redux,什么被认为是普通对象?
例如以下是否也被认为是普通对象?
let a = {
b: {
c: 'd'
}
};
Redux 声明操作必须是普通对象,但是如果我有以下数据在一段时间后进入并且需要将其添加到状态中怎么办。
let payload = {
all: ['john', 'jane'],
byId: {
john: {
name: 'john',
age: 23
},
jane: {
name: 'jane',
age: 40
}
}
}
我想要一个 Action :
function userLoad(payload) {
return { type: USER_LOAD, payload }
}
但如果有效载荷不是普通对象,则这不是好的做法。如何处理此类情况。
最佳答案
普通对象或 POJO(普通 javascript 对象)是通过以下方式创建的对象:
let foo = {prop1: 1} // object literal
let bar = new Object(); // new object syntax
POJO 和通过构造函数创建的对象的区别如下:
function Person (name) {
this.name = name;
}
let me = new Person('willem') // this object is not a POJO
console.log(Object.getPrototypeOf(me) === Person.prototype); // prototype is Person
let POJO = {};
console.log(Object.getPrototypeOf(POJO) === Object.prototype); // POJO prototype is always Object not the prototype property of the constructor functoin. This is the difference
关于javascript - 什么被认为是普通对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52001739/