forked from robdodson/JavaScript-Design-Patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
80 lines (72 loc) · 2.31 KB
/
main.js
File metadata and controls
80 lines (72 loc) · 2.31 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
"use strict";
// Polyfill -- Only necessary for browsers which don't support Object.create. Check this ES5 compatibility table:
// http://kangax.github.com/es5-compat-table/
if (!Object.create) {
Object.create = function (o) {
if (arguments.length > 1) {
throw new Error('Object.create implementation only accepts the first parameter.');
}
function F() {}
F.prototype = o;
return new F();
};
}
// Credit to Yehuda Katz for `fromPrototype` function
// http://yehudakatz.com/2011/08/12/understanding-prototypes-in-javascript/
var fromPrototype = function(prototype, object) {
var newObject = Object.create(prototype);
for (var prop in object) {
if (object.hasOwnProperty(prop)) {
newObject[prop] = object[prop];
}
}
return newObject;
};
// Define the Pizza product
var Pizza = {
description: 'Plain Generic Pizza'
};
// And the basic PizzaStore
var PizzaStore = {
createPizza: function(type) {
if (type == 'cheese') {
return fromPrototype(Pizza, {
description: 'Cheesy, Generic Pizza'
});
} else if (type == 'veggie') {
return fromPrototype(Pizza, {
description: 'Veggie, Generic Pizza'
});
}
}
};
var ChicagoPizzaStore = fromPrototype(PizzaStore, {
createPizza: function(type) {
if (type == 'cheese') {
return fromPrototype(Pizza, {
description: 'Cheesy, Deep-dish Chicago Pizza'
});
} else if (type == 'veggie') {
return fromPrototype(Pizza, {
description: 'Veggie, Deep-dish Chicago Pizza'
});
}
}
});
var CaliforniaPizzaStore = fromPrototype(PizzaStore, {
createPizza: function(type) {
if (type == 'cheese') {
return fromPrototype(Pizza, {
description: 'Cheesy, Tasty California Pizza'
});
} else if (type == 'veggie') {
return fromPrototype(Pizza, {
description: 'Veggie, Tasty California Pizza'
});
}
}
});
// Elsewhere in our app...
var chicagoStore = Object.create(ChicagoPizzaStore);
var pizza = chicagoStore.createPizza('veggie');
console.log(pizza.description); // returns 'Veggie, Deep-dish Chicago Pizza'