3 Way to Call Function var big = function () {/*...*/}; var foo = { small: function () {/*...*/} }; big(); // 1. this: window object foo.small(); // 2. this: foo var small = foo.small; small();
3 Way to Call Function var big = function () {/*...*/}; var foo = { small: function () {/*...*/} }; big(); // 1. this: window object foo.small(); // 2. this: foo var small = foo.small; small(); // 3. this: window object
this in Event Handler // W3C Dom aElement.addEventListener('click', function () { this; // aElement }, false); // old IE aElement.attachEvent('onclick', function () { this; // window });
that/self function Foobar(input) { var that = this; // that or self this.prefix = input; this.echo = function (result) { return that.prefix + result; // that is accessible because of closure }; } fb = new Foobar('res: '); $.get('/info', fb.echo);
How about AMD • Define modules can return constructor, function, array, primitive data • Define a singleton module on most cases • Always have data on module
to new or not to new var p1 = Person('2013/01/02'); p1.getBirth(); // "2013/01/02" var p2 = new Person('2000/01/02', 'F'); p2.getBirth(); // "2000/01/02" p1.getBirth(); // "2013/01/02"
Trade-Off • ‘Not use this’ requires more memory on methods definition and not easy to inheritance object • Benefit is you can write more clear, simple code