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
-
1It 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– Felix Kling2014年05月18日 22:36:14 +00:00Commented May 18, 2014 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: 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– HMR2014年05月19日 00:31:06 +00:00Commented May 19, 2014 at 0:31
1 Answer 1
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);
1 Comment
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.