forked from chuanxshi/javascript-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcp2-rent-a-constructor.html
More file actions
60 lines (49 loc) · 1.27 KB
/
Copy pathcp2-rent-a-constructor.html
File metadata and controls
60 lines (49 loc) · 1.27 KB
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
<!doctype html>
<html lang="en">
<head>
<title>JavaScript Patterns</title>
<meta charset="utf-8">
</head>
<body>
<script>
/* Title: Classical Pattern #2 - Rent a Constructor (a pattern that should be generally avoided)
Description: it borrows the parent constructor, passing the child object to be bound to this and also forwarding any arguments
*/
// the parent constructor
function Parent(name) {
this.name = name || 'Adam';
}
// adding functionality to the prototype
Parent.prototype.say = function () {
return this.name;
};
// child constructor
function Child(name) {
Parent.apply(this, arguments);
}
var kid = new Child("Patrick");
console.log(kid.name); // "Patrick"
// Drawback 1: nothing from the prototype gets inherited
console.log(typeof kid.say); // "undefined"
// Multiple Inheritance by Borrowing Constructors
function Cat() {
this.legs = 4;
this.say = function () {
return "meaowww";
}
}
function Bird() {
this.wings = 2;
this.fly = true;
}
function CatWings() {
Cat.apply(this);
Bird.apply(this);
}
var jane = new CatWings();
console.dir(jane);
// reference
// http://shop.oreilly.com/product/9780596806767.do
</script>
</body>
</html>