Skip to content

Commit fc6a4eb

Browse files
committed
added closure example to decorators
1 parent cac9359 commit fc6a4eb

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

decorator/sale-closures/index.html

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="utf-8">
5+
<title>Decorators: With Closures!</title>
6+
<meta name="description" content="">
7+
<meta name="author" content="">
8+
</head>
9+
<body>
10+
<script type="text/javascript" src="main.js"></script>
11+
</body>
12+
</html>

decorator/sale-closures/main.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
"use strict";
2+
3+
function Sale(price) {
4+
this.price = price || 100;
5+
}
6+
7+
Sale.prototype.getPrice = function() {
8+
return this.price;
9+
};
10+
11+
Sale.prototype.setPrice = function(price) {
12+
this.price = price;
13+
};
14+
15+
function usd(fn, context) {
16+
var price = fn.call(context);
17+
return "$" + price;
18+
}
19+
20+
function decorate(dec, fn, context) {
21+
return function() {
22+
return dec.call(context, fn, context);
23+
};
24+
}
25+
26+
var sale = new Sale(50);
27+
28+
// Decorate our getPrice method. We'll just add
29+
// some extra dollar signs to the output.
30+
sale.getPrice = decorate(usd, sale.getPrice, sale);
31+
sale.getPrice = decorate(usd, sale.getPrice, sale);
32+
sale.getPrice = decorate(usd, sale.getPrice, sale);
33+
console.log(sale.getPrice()); // output: $$$50
34+
35+
// Test to make sure other methods can still
36+
// access the price in the correct context
37+
sale.setPrice(100);
38+
console.log(sale.getPrice()); // output: $$$100

0 commit comments

Comments
 (0)