-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPrototypeInheritance.js
More file actions
39 lines (30 loc) · 1006 Bytes
/
Copy pathPrototypeInheritance.js
File metadata and controls
39 lines (30 loc) · 1006 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
* Human constructor function
*/
var Human = function(name) {
this.name = name;
};
Human.prototype.getName = function() {
return this.name;
};
/**
* Man constructor function 'extends' Human constructor
*/
var Man = function(name) {
Human.apply(this, arguments);
};
Man.prototype = new Human;
// the original prototype constructor of man pointed to the Man constructor, but now we replaced
// the prototype with an instance of Human, the Human constructor was suddenly the constructor
// of our Man constructor. We need to reset that manually to keep access to the constructor
Man.prototype.constructor = Man;
var myMan = new Man('Klaas');
/**
* Tests
*/
console.log(myMan); // output: { name: 'Klaas' }
console.log(myMan instanceof Man); // output: true
console.log(myMan instanceof Human); // output: true
console.log(myMan.__proto__ instanceof Human); // output: true
console.log(myMan.__proto__.constructor === Man); // output: true
console.log(myMan.getName()); // output: Klaas