File tree Expand file tree Collapse file tree 2 files changed +50
-0
lines changed
Expand file tree Collapse file tree 2 files changed +50
-0
lines changed Original file line number Diff line number Diff line change 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 >
Original file line number Diff line number Diff line change 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
You can’t perform that action at this time.
0 commit comments