forked from chuanxshi/javascript-patterns
/
prototypal-inheritance.html
73 lines (62 loc) · 1.38 KB
/
prototypal-inheritance.html
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<!doctype html>
<html lang="en">
<head>
<title>JavaScript Patterns</title>
<meta charset="utf-8">
</head>
<body>
<script>
/* Title: Prototypal Inheritance
Description: objects inherit from other objects
*/
function object(o) {
function F() {}
F.prototype = o;
return new F();
}
// object to inherit from
var parent = {
name: "Papa"
};
// the new object
var child = object(parent);
// testing
alert(child.name); // "Papa"
// parent constructor
function Person() {
// an "own" property
this.name = "Adam";
}
// a property added to the prototype
Person.prototype.getName = function () {
return this.name;
};
// create a new person
var papa = new Person();
// inherit
var kid = object(papa);
// test that both the own property
// and the prototype property were inherited
kid.getName(); // "Adam"
// parent constructor
function Person() {
// an "own" property
this.name = "Adam";
}
// a property added to the prototype
Person.prototype.getName = function () {
return this.name;
};
// inherit
var kid = object(Person.prototype);
typeof kid.getName; // "function", because it was in the prototype
typeof kid.name; // "undefined", because only the prototype was inherited
/* Addition to ECMAScript 5 */
var child = Object.create(parent);
var child = Object.create(parent, {
age: { value: 2 } // ECMA5 descriptor
});
child.hasOwnProperty("age"); // true
</script>
</body>
</html>