Skip to content

Instantly share code, notes, and snippets.

@Williammer
Last active August 29, 2015 14:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Williammer/a103835d3d5910d89ea2 to your computer and use it in GitHub Desktop.
Save Williammer/a103835d3d5910d89ea2 to your computer and use it in GitHub Desktop.
jsPatterns.borrowAndBindProp.js - use apply/call and prototype to implement the function to bind and borrow property from other object.
/* # bind() function - 3 impls that works
* @ sample:
* var newFunc = obj.someFunc.bind(myobj, 1, 2, 3);
*/
//pre ECMA5 bind function:
// 《js Pattern》 version
if (typeof Function.prototype.bind === "undefined") {
Function.prototype.bind = function (thisArg) {
var fn = this,
slice = Array.prototype.slice,
args = slice.call(arguments, 1);
return function () {
return fn.apply(thisArg, args.concat(slice.call(arguments)));
};
};
}
// 《js ninja》 version
if (typeof Function.prototype.bind === "undefined") {
Function.prototype.bind = function() {
var fn = this,
args = Array.prototype.slice.call(arguments),
object = args.shift();
return function() {
return fn.apply(object,
args.concat(Array.prototype.slice.call(arguments)));
};
};
}
// 《js web application》 version
if(!Function.prototype.bind){
Function.prototype.bind = function(obj){
var slice = [].slice,
np = function(){},
args = slice.call(arguments, 1),
self = this,
bound = function(){
return self.apply(this instanceof np? this: (obj || {}),
args.concat( slice.call(arguments)) );
};
np.prototype = self.prototype;
bound.prototype = new np();
return bound;
};
}
//test
var one = {
name: "object",
say: function (greet) {
return greet + ", " + this.name;
}
},
two = {
name: "another object"
},
twosay2 = one.say.bind(two),
twosay3 = one.say.bind(two, 'Enchanté');
twosay2('Bonjour'); // "Bonjour, another object
twosay3(); // "Enchanté, another object"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment