在这种情况下如何覆盖 属性

How can I override property in this situation

我是 JavaScript 的新手,所以如果我误解了某个概念,请随时告诉我。

我有以下 class:

var Human = function () {};
Object.defineProperty(Human.prototype, 'name', {
     get: function () { return this._name; },
     set: function (value) { this._name = value; },
     configurable: true,
     enumerable: true
});

然后我定义了以下子对象:

var Man = function () {};
Man.prototype = new Human(); //Am I inherting Human's prototype (and properties) here?
Man.prototype.name = 'Matt'; //If so, I should be setting Man's name property (overriding the value inherited from Human)

然而,console.log(Man.name) 打印出 ""

为什么会这样,我怎样才能正确覆盖 Human 的 属性?

PS:

我也试过了

Man.name = 'Matt';

而不是

Man.prototype.Name = 'Matt';

但我也有同样的行为。

Ps2:

我还应该注意,如果我执行 console.log(Man.prototype._name) 我会得到预期的输出 "Matt"

由于你设置的是原型属性,你需要从这个构造函数中实例化一个新的对象,然后原型将用于构造新的对象实例:

var Man = function () {};
Man.prototype = new Human();
Man.prototype.name = 'Matt';

var man = new Man(); // <--- this is new man
console.log(man.name);

但是,您可能不希望所有 Man 个实例都具有相同的名称 - 当您将内容放入 prototype 时会发生什么,它会被所有实例共享。这更有意义:

var Man = function () {};
Man.prototype = new Human();

var man = new Man();
man.name = 'Matt';
console.log(man.name);

这里只设置对象man.

own属性