Function.prototype.bind example
by desandro
HTML
<p>Click to set new position, and a new color, after a delay</p>
CSS
body { font-family: sans-serif; }
JavaScript
// Without Function.prototype.bind
function Ball( size ) {
this.elem = document.createElement('div');
this.size = size;
this.elem.style.width = size + 'px';
this.elem.style.height = size + 'px';
this.elem.style.borderRadius = ( size * 0.5 ) + 'px';
this.elem.style.position = 'absolute';
this.x = 100;
this.y = 100;
this.setRandomColor();
this.render();
document.body.appendChild( this.elem );
document.addEventListener( 'mousedown', this, false );
}
Ball.prototype.render = function() {
this.elem.style.left = ( this.x - this.size * 0.5 ) + 'px';
this.elem.style.top = ( this.y - this.size * 0.5 ) + 'px';
};
Ball.prototype.setRandomColor = function() {
var hue = Math.floor( Math.random() * 360 );
this.elem.style.backgroundColor = 'hsl(' + hue + ', 100%, 50% )';
};
// ----- event handling ----- //
// allows for handler that matches event type to be triggered
// i.e. mousedown -> .mousedownHandler()
Ball.prototype.handleEvent = function( event ) {
var handler = event.type + 'Handler';
if ( this[ handler ] ) {
this[ handler ]( event );
}
};
Ball.prototype.mousedownHandler = function( event ) {
this.x = event.pageX;
this.y = event.pageY;
this.render();
// set different color after delay
var _this = this;
setTimeout( function() {
_this.setRandomColor();
}, 500 );
};
// ----- init ----- //
window.onload = function() {
window.myBall = new Ball( 50 );
};