Function.prototype.bind example
by OmShiv
HTML
<p>Click anywhere to set a new position and color, after some delay</p>
CSS
body { font-family: sans-serif; font-size: 12px; }
p {
padding: 10px;
}
JavaScript
// WITH Function.prototype.bind
// ----- Function.prototype.bind polyfill ----- //
if (!Function.prototype.bind) {
Function.prototype.bind = function bind(that) {
var target = this;
if (typeof target != "function") {
throw new TypeError();
}
var args = slice.call(arguments, 1),
bound = function () {
if (this instanceof bound) {
var F = function(){};
F.prototype = target.prototype;
var self = new F;
var result = target.apply(
self,
args.concat(slice.call(arguments))
);
if (Object(result) === result) {
return result;
}
return self;
} else {
return target.apply(
that,
args.concat(slice.call(arguments))
);
}
};
return bound;
};
}
// ----- Ball ----- //
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.mousedownHandler.bind( 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 ----- //
Ball.prototype.mousedownHandler = function( event ) {
this.x = event.pageX;
this.y = event.pageY;
this.render();
// set different color after delay
setTimeout( this.setRandomColor.bind( this ), 500 );
};
//...