From 4e445995d85e711cb9bac76a4549405f370c97f7 Mon Sep 17 00:00:00 2001 From: Kyle K Date: Fri, 29 Jun 2012 23:40:29 -0500 Subject: add some examples, why the heck not, humans forget stuff --- samples/call_method.js | 20 ++++++++++++++++++++ samples/middleware.js | 24 ++++++++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 samples/call_method.js create mode 100644 samples/middleware.js 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); + -- cgit v1.2.3