是否有Object.prototype.hasOwnProperty的对应项?

时间:2019-10-24 07:15:18

标签: javascript ecmascript-6 properties

给出以下示例类结构:

class matter {
  constructor(atomicNumber) {
    this.atomicNumber = atomicNumber;
  }
}

class stone extends matter {
  constructor(atomicNumber, mohsHardness) {
    super(atomicNumber);
    this.mohsHardness = mohsHardness;
  }

  showProperties() {
    console.log(Object.getOwnPropertyNames(this));
  }
}

class gem extends stone {
  constructor(atomicNumber, mohsHardness, carat) {
    super(atomicNumber, mohsHardness);
    this.carat = carat;
  }
}

let chunk = new gem(6, 10, 1);
chunk.showProperties();

功能Object.getOwnPropertyNames的输出符合预期,

['atomicNumber', 'mohsHardness', 'carat']

我将如何获得“父”类的属性,就像那样?

['atomicNumber', 'mohsHardness']

如果我替换这样的函数:

showProperties() {
    const parentClass = Object.getPrototypeOf(Object.getPrototypeOf(this));
    console.log(Object.getOwnPropertyNames(parentClass));
}

我得到结果

['constructor', 'showProperties']

这让我很茫然。也许与Object.prototype.hasOwnProperty相对应?

1 个答案:

答案 0 :(得分:2)

问题在于,创建子实例时,thismatter构造函数中引用的stone与对象中引用的this完全相同。子构造函数(gem)。子构造函数更改实例后,无法将子构造函数添加的属性与超级构造函数添加的属性区分开。

执行此类操作的唯一方法是在super调用完成之后,在子构造函数更改对象之前检查对象:

class matter {
    constructor(atomicNumber) {
        this.atomicNumber = atomicNumber;
    }
}

class stone extends matter {
    constructor(atomicNumber, mohsHardness) {
        super(atomicNumber);
        this.mohsHardness = mohsHardness;
    }

    showProperties() {
        console.log(this.parentProperties);
    }
}

class gem extends stone {
    constructor(atomicNumber, mohsHardness, carat) {
        super(atomicNumber, mohsHardness);
        this.parentProperties = Object.getOwnPropertyNames(this);
        this.carat = carat;
    }
}

let chunk = new gem(6, 10, 1);
chunk.showProperties();