9. 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();
10. 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
11. Borrowing Method
var foo = {
small: function () {
this;
}
};
var bar = {};
foo.small(); // this: foo
bar.borrowedSmall = foo.small;
bar.borrowedSmall(); // this: bar
22. Implement Bind
var bind = function (func, context) {
return function () {
func.apply(context, arguments);
};
};
23. Solve Event Handler
• Use apply to assign context
• JavaScript Libraries did it for you
24. this in Event Handler
// W3C Dom
aElement.addEventListener('click', function () {
this; // aElement
}, false);
// old IE
aElement.attachEvent('onclick', function () {
this; // window
});
25. Callback Function
function Foobar (input) {
this.prefix = input;
}
Foobar.prototype.echo = function (result) {
return this.prefix + result;
};
fb = new Foobar();
$.get('/info', function (result) {
fb.echo(result);
});
26. Reduce One Stack
function Foobar (input) {
this.prefix = input;
}
Foobar.prototype.echo = function (result) {
return this.prefix + result;
};
fb = new Foobar();
$.get('/info', fb.echo); // this.prefix is 'undefined'
27. Use bind
function Foobar (input) {
this.prefix = input;
this.echo = this.echo.bind(this); // Protect method
}
Foobar.prototype.echo = function (result) {
return this.prefix + result;
};
fb = new Foobar();
$.get('/info', fb.echo);
36. Closure
var isIE = true;
function foobar() {
if (!isIE) {
// access isIE is possible because of closure
return;
}
// blah...
};
37. 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);
46. How about AMD
• Define modules can return constructor,
function, array, primitive data
• Define a singleton module on most cases
• Always have data on module
47. AMD Singleton Module
define('foobar', function () {
return {
init: function (prefix) {
this.prefix = prefix;
}
echo: function (input) {
return this.prefix + input;
}
};
});
51. Constructor Without
this
function Person(birth, gender) {
var person = {
birth: (birth || '1970/01/01'),
gender: (gender || 'M')
};
return {
getBirth: function () {
return person.birth;
},
getGender: function () {
return person.gender;
}
};
}
52. 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"
61. 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