Skip to content

Instantly share code, notes, and snippets.

@kaaes
kaaes / context_pitfall_ex3.js
Created May 19, 2011 15:10
Watch out for context part 3
var el = document.getElementById('showCounterTrigger');
el.onclick = function(evt) { logger.getCounter() }
// if you're operating in ECMA5 environment (webkit or gecko)
// you can also use bind() (more about bind below)
el.onclick = logger.getCounter.bind(logger);
// just remember that every event callback has an event object
// passed as a first parameter, so be careful when reusing methods
@kaaes
kaaes / context_pitfall_ex2.js
Created May 19, 2011 15:09
Watch out for context part 2
var el = document.getElementById('showCounterTrigger');
el.onclick = logger.getCounter
@kaaes
kaaes / context_pitfall_ex.js
Created May 19, 2011 15:06
Watch out for context part 1
// create Logger constructor with few properties
var Logger = function(id) {
this.container = document.getElementById(id);
this.counter = 0;
}
// add functionalities with prototype
Logger.prototype.log = function(msg) {
this.container.innerHTML = msg ;
this.counter++;
@kaaes
kaaes / simple_this_ex.js
Created May 19, 2011 15:02
basic example of this object
var a, b, c, d, e;
a = function(obj) {
return this;
}
// when you call the function in 'function form' 'this' is window object
a(); // window
@kaaes
kaaes / bind_ex.js
Created May 19, 2011 14:59
bind() example
function sum () {
var s = 0;
for (var i = 0, len = arguments. length; i < len; i++) {
s += arguments[i];
}
return s;
}
// execute function and
// return 6, context is window
@kaaes
kaaes / that_self_ex.js
Created May 19, 2011 14:54
Example of that/self workaround
var JSobj = function(id) {
var that = this;
var date = new Date();
that.id = 'JSnode_' + id;
that.element = document.getElementById(id);
that.createdAt = date.getTime();
that.element.addEventListener('click', clickCallback, false);