简体   繁体   English

Object.create没有创建属性

[英]Object.create not creating properties

I have the following function 我有以下功能

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 }

If I change the Object.create(this, {users: filtered}) with this.users = filtered; return this; 如果我用this.users = filtered; return this;更改Object.create(this, {users: filtered}) this.users = filtered; return this; this.users = filtered; return this; it "works", but I don't want to change the state of my original object. 它“有效”,但我不想改变原始对象的状态。 Any thoughts? 有什么想法吗?

The "properties" optional argument to Object.create() should not be just an ordinary object. Object.create()的“properties”可选参数不应该只是一个普通的对象。 Instead, it should look like the argument to Object.defineProperties() : 相反,它应该看起来像Object.defineProperties()的参数:

   return Object.create(this, {
     users: { value: filtered }
   });

And if you want the property to be enumerable and writable etc, you have to explicitly mention that: 如果你想要属性可枚举和可写等,你必须明确提到:

   return Object.create(this, {
     users: { 
       value: filtered,
       enumerable: true,
       writable: true
     }
   });

As is pointed out in a comment below, having that function return a new object created with the called context as the prototype sure looks strange. 正如下面的评论中所指出的那样,让该函数返回一个使用被调用上下文创建的新对象,因为原型肯定看起来很奇怪。 I'm not sure why you wouldn't just 我不确定你为什么不这样做

   return new Admin(filtered, this.affiliation);

or something else less exotic. 或其他不那么奇特的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM