在这种情况下我如何重写属性

How can I override property in this situation

本文关键字:重写 属性 何重写 这种情况下      更新时间:2023-09-26

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

我有以下类:

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的属性?

p :

我也试过

Man.name = 'Matt';
不是

Man.prototype.Name = 'Matt';

但我得到了同样的行为。

Ps2:

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

因为你正在设置prototype属性,你需要从这个构造函数实例化一个新对象,然后prototype将被用来构造新的对象实例:

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属性。