1

I'm new to JavaScript so if I'm misunderstanding a concept, please feel free to let me know.

I have the following class:

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

I then define the following child object:

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)

However, console.log(Man.name) prints out "".

Why is this and how can I correctly override Human's property?

PS:

I have also tried

Man.name = 'Matt';

instead of

Man.prototype.Name = 'Matt';

But I got the same behaviour.

Ps2:

I should also note that if I execute console.log(Man.prototype._name) i get the expected output "Matt"

Matias Cicero
  • 25,439
  • 13
  • 82
  • 154
  • `Man.name` is the _function name_, which has nothing to do with that `name` property. If you did `var Man = function someName(){};`, `Man.name` would be `"someName"`. Anyway, what exactly is your expected behavior? – Sebastian Simon Sep 01 '15 at 19:14

1 Answers1

2

Since you are setting prototype property, you need to instantiate a new object from this constructor, then prototype will be used to construct new object instance:

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

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

However, you probably don't want all Man instancies to have the same name - what happens when you put stuff in prototype, it's get shared by all instancies. This makes more sense:

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

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

Here you only set own property of the the object man.

dfsq
  • 191,768
  • 25
  • 236
  • 258
  • This is the exact behaviour that I wanted to achieve. Defining a property in a super class and overwriting it in the child. Thank you! – Matias Cicero Sep 01 '15 at 19:18