Permalink
Browse files

Merge pull request #16 from der-On/master

added core.bind()
  • Loading branch information...
2 parents 6991d32 + ac5742b commit 51250c4bb58208b4531d0693b1ecc157692386ea @mde committed Feb 28, 2014
Showing with 41 additions and 0 deletions.
  1. +19 −0 lib/core.js
  2. +22 −0 test/core.js
View
@@ -101,6 +101,25 @@ 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') {
+ if (typeof Function.bind === 'function') {
+ return fn.bind.apply(self, curryArgs);
+ }
+ else {
+ return fn.apply(self, curryArgs);
+ }
+ } 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 51250c4

Please sign in to comment.