diff options
author | Kyle K <kylek389@gmail.com> | 2012-06-29 23:40:29 -0500 |
---|---|---|
committer | Kyle Kaminski <kyle@kkaminsk.com> | 2012-06-29 23:40:29 -0500 |
commit | 4e445995d85e711cb9bac76a4549405f370c97f7 (patch) | |
tree | 06ff2750aa763b2c4d8afa58027e4949c0b1c906 /samples | |
parent | a1d9689c5df0bdaf49a42e4682742e344665791a (diff) | |
download | fubar-4e445995d85e711cb9bac76a4549405f370c97f7.tar.gz fubar-4e445995d85e711cb9bac76a4549405f370c97f7.tar.bz2 fubar-4e445995d85e711cb9bac76a4549405f370c97f7.zip |
add some examples, why the heck not, humans forget stuff
Diffstat (limited to 'samples')
-rw-r--r-- | samples/call_method.js | 20 | ||||
-rw-r--r-- | samples/middleware.js | 24 |
2 files changed, 44 insertions, 0 deletions
diff --git a/samples/call_method.js b/samples/call_method.js new file mode 100644 index 0000000..a227562 --- /dev/null +++ b/samples/call_method.js @@ -0,0 +1,20 @@ +/* shows how to use call() and apply() + * essentially give a method called .bar(), instead of calling it directly with + * use of dobule parens we append .call(instance [, arg1, arg2, ...]), where + * apply takes array of args + */ + +function foo() { + this.tag = 'bar'; + this.bar = function(txt) { + console.log(txt + this.tag); + } +} + +var bar = new foo(); +bar.bar('foo') +/* first arg of call is the class instance, could be 'this' if we were in one */; +bar.bar.call(bar, 'foo'); +/* apply is similar but it accepts on array of arguments */ +bar.bar.apply(bar, ['foo']); + diff --git a/samples/middleware.js b/samples/middleware.js new file mode 100644 index 0000000..e572d10 --- /dev/null +++ b/samples/middleware.js @@ -0,0 +1,24 @@ +function foo() { + this.tag = 'bar' + this.bar = function(txt) { + console.log('hello ' + txt); + } +} + +var bar = new foo(); + +function middleware(foo) { + oldbar = foo.bar; /* save old function, don't make a reference! */ + foo.bar = function(txt) { + /* ah, here's our chance to mutate txt argument! */ + txt = 'dozed off ' + txt; + oldbar(txt); + } + + foo.newtag = 'muhahaha'; +} + +middleware(bar); /* mutate! */ +bar.bar('kyle'); +console.log(bar.newtag); + |