Object.create 未创建属性
Object.create not creating properties
我有以下功能
const Admins = function(users, affiliation) {
this.users = users;
this.affiliation = affiliation;
}
Admins.prototype.filterAffiliation = function _filterAffiliation() {
const filtered = this.users.filter( (user) => {
return user.affiliation === this.affiliation;
});
console.log(filtered); // this shows the array of users filtered
return Object.create(this, { users: filtered });
}
const admins = new Admins(users, affiliation);
console.log(admins); // this shows everything correctly...
admins.filterAffiliation() // this shows { users: undefined }
如果我将 Object.create(this, {users: filtered})
更改为 this.users = filtered; return this;
它 "works",但我不想更改原始对象的状态。有什么想法吗?
Object.create()
的 "properties" 可选参数不应该只是一个普通对象。相反,它应该看起来像 Object.defineProperties()
:
的参数
return Object.create(this, {
users: { value: filtered }
});
如果您希望 属性 可枚举和可写等,您必须明确提及:
return Object.create(this, {
users: {
value: filtered,
enumerable: true,
writable: true
}
});
正如在下面的评论中指出的那样,使用该函数 return 创建一个使用被调用上下文作为原型的新对象确实看起来很奇怪。我不确定你为什么不
return new Admin(filtered, this.affiliation);
或其他不那么奇特的东西。
我有以下功能
const Admins = function(users, affiliation) {
this.users = users;
this.affiliation = affiliation;
}
Admins.prototype.filterAffiliation = function _filterAffiliation() {
const filtered = this.users.filter( (user) => {
return user.affiliation === this.affiliation;
});
console.log(filtered); // this shows the array of users filtered
return Object.create(this, { users: filtered });
}
const admins = new Admins(users, affiliation);
console.log(admins); // this shows everything correctly...
admins.filterAffiliation() // this shows { users: undefined }
如果我将 Object.create(this, {users: filtered})
更改为 this.users = filtered; return this;
它 "works",但我不想更改原始对象的状态。有什么想法吗?
Object.create()
的 "properties" 可选参数不应该只是一个普通对象。相反,它应该看起来像 Object.defineProperties()
:
return Object.create(this, {
users: { value: filtered }
});
如果您希望 属性 可枚举和可写等,您必须明确提及:
return Object.create(this, {
users: {
value: filtered,
enumerable: true,
writable: true
}
});
正如在下面的评论中指出的那样,使用该函数 return 创建一个使用被调用上下文作为原型的新对象确实看起来很奇怪。我不确定你为什么不
return new Admin(filtered, this.affiliation);
或其他不那么奇特的东西。