Skip to content

Instantly share code, notes, and snippets.

@kaaes
Created May 19, 2011 15:11
Show Gist options
  • Save kaaes/980983 to your computer and use it in GitHub Desktop.
Save kaaes/980983 to your computer and use it in GitHub Desktop.
Watch out for context part 4
el.onclick = function(evt) {
this.style.backgroundColor = '#f00';
this.style.borderBottom = 'solid 2px blue';
}
el2.onclick = function(evt) {
this.style.backgroundColor = '#ff0';
this.style.borderBottom = 'dotted 1px green';
}
// refactor to avoid redundancy
function addStyle(bgColor, border) {
this.style.backgroundColor = bgColor;
this.style.borderBottom = border;
}
// it WON'T work because function will be called in context of window!
el.onclick = function(evt) {
addStyle('#f00', 'solid 2px blue')
}
el2.onclick = function(evt) {
addStyle('#ff0', 'dotted 1px green')
}
// to make it properly you have to either pass
// the HTML element as parameter...
function addStyle(el, bgColor, border) {
el.style.backgroundColor = bgColor;
el.style.borderBottom = border;
}
el.onclick = function(evt) {
addStyle(this, '#f00', 'solid 2px blue')
}
el2.onclick = function(evt) {
addStyle(this, '#ff0', 'dotted 1px green')
}
// ...or force the context with call/apply
function addStyle(bgColor, border) {
this.style.backgroundColor = bgColor;
this.style.borderBottom = border;
}
el.onclick = function(evt) {
addStyle.call(this, '#f00', 'solid 2px blue');
}
el2.onclick = function(evt) {
addStyle.call(this, '#ff0', 'dotted 1px green')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment