I’ve written a bind function that binds the given parameters to the designated function as a practice.
<script type='text/javascript'>
// 'method' is taken from Douglas Crockford's Javascript: The Good Parts, Oreilly.
// This is a good to have shorthand for adding a method to Object.
Object.prototype.method = function(method_name, func) {
Object.prototype[method_name] = func;
}
Object.method('bind', function() {
// Here, 'this' is the context where 'bind' is called. So, it is 'add' in the examples below.
var target_func = this;
// Parameters passed to bind.
// 'arguments' is not Array thought it's arraylike object, so we convert it to Array.
var partial_args = Array.prototype.slice.call(arguments);
// A function that will accept the remained parameters.
return function(remained_params) {
// Call target function with partial and the remained parameters combined.
return target_func.apply(null,
partial_args.concat(Array.prototype.slice.call(arguments)));
}
});
var add = function(a, b) {
return a + b;
}
var addToOne = add.bind(1);
document.write('addToOne: ' + addToOne(2) + '<br>'); // 3
var add3 = function(a, b, c) {
return a + b + c;
}
var addToOne3 = add3.bind(3);
document.write('addToOne3: ' + addToOne3(4, 5) + '<br>'); // 12
var addToOneTwo3 = add3.bind(6, 7);
document.write('addToOneTwo3: ' + addToOneTwo3(8) + '<br>'); // 21
</script>
Post a Comment