Permalink
Browse files

added core.bind()

  • Loading branch information...
der-On committed Feb 28, 2014
1 parent 3043e67 commit 9132d13c151db805434e3324527c2998faf8a5ba
Showing with 45 additions and 0 deletions.
  1. +23 −0 lib/core.js
  2. +22 −0 test/core.js
View
@@ -101,6 +101,29 @@ var core = new (function () {
return false;
};
+ /*
+ binds a function to an object
+ */
+ this.bind = function(self, fn)
+ {
+ var curryArgs = arguments.length > 2 ? Array.prototype.slice.call(arguments, 2) : [];
+ if (typeof fn === 'function' && !(fn instanceof RegExp)) {
+ return curryArgs.length
+ ? function () {
+ return arguments.length
+ ? fn.apply(self, curryArgs.concat(slice.call(arguments, 0)))
+ : fn.apply(self, curryArgs);
+ }
+ : function () {
+ return arguments.length
+ ? fn.apply(self, arguments)
+ : fn.call(self);
+ };
+ } else {
+ // in IE, native methods are not functions so they cannot be bound (note: they don't need to be)
+ return fn;
+ }
+ }
})();
module.exports = core;
View
@@ -69,7 +69,29 @@ tests = {
, 'isEmpty, zero (false)': function () {
assert.ok(!core.isEmpty(0));
}
+,
+ 'bind': function () {
+ function bar() {}
+ function foo() {
+ assert.equal(this.name, 'bar');
+ }
+
+ var fooBoundToBar = core.bind(bar, foo);
+ fooBoundToBar();
+ }
+,
+ 'bind, arguments': function () {
+ function bar() {}
+
+ function foo(arg) {
+ assert.equal(this.name, 'bar');
+ assert.equal(arg, 'cats');
+ }
+
+ var fooBoundToBarWithCats = core.bind(bar, foo, 'cats');
+ fooBoundToBarWithCats();
+ }
};
module.exports = tests;

0 comments on commit 9132d13

Please sign in to comment.