1

The Introduction to Object-Oriented JavaScript is confusing me at one point.

They define a Person class like this:

Properties should be set in the prototype property of the class (function) so that inheritance works correctly.

function Person(gender) {
  this.gender = gender;
  alert('Person instantiated');
}

Person.prototype.gender = '';

Later when they give an example of inheritance, they remove the gender property (for clarity I assume), so I am not sure what the line Person.prototype.gender = ''; does in the first place.

I tried this:

function Person(gender) {
  this.gender = gender;
}

Person.prototype.gender = 'default';

function Student(gender) {
  Person.call(this, gender);
};

Student.prototype = new Person();
Student.prototype.constructor = Student;


var a = new Student('male');
var b = new Student();

console.log(a.gender); //prints 'male'
console.log(b.gender); //I expect 'default', but get undefined
newprogrammer
  • 2,514
  • 2
  • 28
  • 46
  • 1
    It doesn't do anything since you are setting a property with the same name on the object itself, which shadows the property on the prototype. But some tools might require this and it also might make the interface of your "class" clearer. – Felix Kling May 18 '14 at 22:36
  • If you would like to know how JavaScript uses the prototype to look up properties and what shadowing is then you can read this answer: http://stackoverflow.com/a/16063711/1641941 it covers it in more details and with some examples. Also some problems you might solve by using Object.create and how to pass constructor parameters (or parameters to a chain of functions in general). – HMR May 19 '14 at 00:31

1 Answers1

2

You must not set the property directly on the object if you want to inherit it's value from the prototype.

function Person(gender) {
  if (typeof gender !== 'undefined') this.gender = gender;
}

Also, avoid newing up objects when the only goal is to setup the prototype chain. Using new like below might have undesirable side effects in some cases.

Student.prototype = new Person();

Should be replaced by:

Student.prototype = Object.create(Person.prototype);
plalx
  • 42,889
  • 6
  • 74
  • 90
  • 1
    Just a reminder that `Object.create()` requires IE9+. Not everyone has given up on supporting IE8 yet (many have, but not all) and most of the time `new x()` doesn't have a side effect. – jfriend00 May 18 '14 at 23:06