<!-- Based on the code from Douglas Crockford, Chap 4. Functions, Javascript: The Good Parts, Oreilly. Print ISBN: 978-0-596-51774-8 | ISBN 10: 0-596-51774-2 Ebook ISBN: 978-0-596-15873-6 | ISBN 10: 0-596-15873-4 --> <html> <body> <pre> <script> // Method document.writeln('Method call'); var obj = { value: 0, increment: function(inc) { this.value += typeof inc == 'number' ? inc : 1; } } obj.increment(); document.writeln(obj.value); // 1 obj.increment(2); document.writeln(obj.value); // 3 // Function document.writeln('Function call'); var value = 0; function f() { this.value += 1; } document.writeln(value); // 0 f(); document.writeln(value); // 1 // Workaround for 'this' in a nested function of a method. document.writeln('Nested function call'); var obj2 = { value: 0, increment: function() { var that = this; // points to obj2 function h() { that.value += 1; // 'this' inside h() points to global namespace. } h(); } } document.writeln(obj2.value); // 0 obj2.increment(); document.writeln(obj2.value); // 1 // Constructor and the use of prototype. document.writeln('Constructor and prototype'); var Foo = function(string) { this.name = string; } Foo.prototype.print_name = function() { document.writeln(this.name); } var f = new Foo("foo"); f.print_name(); // "foo" // Apply document.writeln('Apply'); var obj3 = { val:1, bar: function() { document.writeln(this.val); } } var obj4 = { val: 2 } obj3.bar.apply(obj4); // 2 </script> </pre> </body> </html>
prototype and apply looks very interesting. It feels like some lego blocks that I can assemble with great flexibility.