diff options
Diffstat (limited to 'samples/call_method.js')
-rw-r--r-- | samples/call_method.js | 20 |
1 files changed, 20 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']); + |