forked from chuanxshi/javascript-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcp1-default.html
50 lines (41 loc) · 1.2 KB
/
cp1-default.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
<!doctype html>
<html lang="en">
<head>
<title>JavaScript Patterns</title>
<meta charset="utf-8">
</head>
<body>
<script>
/* Title: Classical Pattern #1 - The Default Pattern (a pattern that should be generally avoided)
Description: create an object using the Parent() constructor and assign this object to the Child()'s prototype
*/
function inherit(C, P) {
C.prototype = new P();
}
// the parent constructor
function Parent(name) {
this.name = name || 'Adam';
}
// adding functionality to the prototype
Parent.prototype.say = function () {
return this.name;
};
// empty child constructor
function Child(name) {
}
// inheritance magic happens here
inherit(Child, Parent);
var kid = new Child();
console.log(kid.say()); // "Adam"
// Drawback 1: own properties added to `this` is inherited
var kiddo = new Child();
kiddo.name = "Patrick";
console.log(kiddo.say()); // "Patrick"
// Drawback 2: it doesn't enable you to pass parameters to the child constructor
var s = new Child('Seth');
console.log(s.say()); // "Adam"
// reference
// http://shop.oreilly.com/product/9780596806767.do
</script>
</body>
</html>