Closes #47. More conforming Function.prototype.bind.

This commit is contained in:
kangax 2011-08-29 12:09:32 -04:00
parent 709348f96f
commit 8ea5f0d52c
3 changed files with 54 additions and 15 deletions

26
dist/all.js vendored
View file

@ -2136,7 +2136,8 @@ fabric.util.string = {
(function() {
var slice = Array.prototype.slice,
apply = Function.prototype.apply;
apply = Function.prototype.apply,
dummy = function() { };
if (!Function.prototype.bind) {
/**
@ -2146,12 +2147,23 @@ fabric.util.string = {
* @param {Any[]} [...] Values to pass to a bound function
* @return {Function}
*/
Function.prototype.bind = function(thisArg) {
var fn = this, args = slice.call(arguments, 1);
return args.length
? function() { return apply.call(fn, thisArg, args.concat(slice.call(arguments))); }
: function() { return apply.call(fn, thisArg, arguments) };
};
Function.prototype.bind = function(thisArg) {
var fn = this, args = slice.call(arguments, 1), bound;
if (args.length) {
bound = function() {
return apply.call(fn, this instanceof dummy ? this : thisArg, args.concat(slice.call(arguments)));
};
}
else {
bound = function() {
return apply.call(fn, this instanceof dummy ? this : thisArg, arguments);
};
}
dummy.prototype = this.prototype;
bound.prototype = new dummy;
return bound;
};
}
})();

View file

@ -1,7 +1,8 @@
(function() {
var slice = Array.prototype.slice,
apply = Function.prototype.apply;
apply = Function.prototype.apply,
dummy = function() { };
if (!Function.prototype.bind) {
/**
@ -11,12 +12,23 @@
* @param {Any[]} [...] Values to pass to a bound function
* @return {Function}
*/
Function.prototype.bind = function(thisArg) {
var fn = this, args = slice.call(arguments, 1);
return args.length
? function() { return apply.call(fn, thisArg, args.concat(slice.call(arguments))); }
: function() { return apply.call(fn, thisArg, arguments) };
};
Function.prototype.bind = function(thisArg) {
var fn = this, args = slice.call(arguments, 1), bound;
if (args.length) {
bound = function() {
return apply.call(fn, this instanceof dummy ? this : thisArg, args.concat(slice.call(arguments)));
};
}
else {
bound = function() {
return apply.call(fn, this instanceof dummy ? this : thisArg, arguments);
};
}
dummy.prototype = this.prototype;
bound.prototype = new dummy;
return bound;
};
}
})();

View file

@ -1,4 +1,4 @@
(function(){
(function() {
module('fabric.util');
@ -166,6 +166,21 @@
bound = fn.bind(obj, 1);
same([obj, 1, undefined], bound());
same([obj, 1, 2], bound(2));
function Point(x, y) {
this.x = x;
this.y = y;
}
var obj = { }
var YAxisPoint = Point.bind(obj, 0);
var axisPoint = new YAxisPoint(5);
same(0, axisPoint.x);
same(5, axisPoint.y);
ok(axisPoint instanceof Point);
// ok(axisPoint instanceof YAxisPoint); <-- fails
});
test('fabric.util.getById', function() {