summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--samples/call_method.js20
-rw-r--r--samples/middleware.js24
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);
+