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
74 lines (66 loc) · 1.97 KB
/
main.js
File metadata and controls
74 lines (66 loc) · 1.97 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
"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 our `Ingredients` base object
var Ingredients = {
createDough: function() {
return 'generic dough';
},
createSauce: function() {
return 'generic sauce';
},
createCrust: function() {
return 'generic crust';
}
};
// Extend `Ingredients` with concrete implementations
Ingredients.createChicagoStyle = function() {
return fromPrototype(Ingredients, {
createDough: function() {
return 'thick, heavy dough';
},
createSauce: function() {
return 'rich marinara';
},
createCrust: function() {
return 'deep-dish';
}
});
};
Ingredients.createCaliforniaStyle = function() {
return fromPrototype(Ingredients, {
createDough: function() {
return 'light, fluffy dough';
},
createSauce: function() {
return 'tangy red sauce';
},
createCrust: function() {
return 'thin and crispy';
}
});
};
// Try it out!
var californiaIngredients = Ingredients.createCaliforniaStyle();
console.log(californiaIngredients.createCrust()); // returns 'thin and crispy';