2023-07-29 20:33:28 +02:00
|
|
|
'use strict';
|
|
|
|
|
|
|
|
/* eslint no-invalid-this: 1 */
|
|
|
|
|
|
|
|
var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
|
|
|
|
var toStr = Object.prototype.toString;
|
2024-08-26 08:36:01 +02:00
|
|
|
var max = Math.max;
|
2023-07-29 20:33:28 +02:00
|
|
|
var funcType = '[object Function]';
|
|
|
|
|
2024-08-26 08:36:01 +02:00
|
|
|
var concatty = function concatty(a, b) {
|
|
|
|
var arr = [];
|
|
|
|
|
|
|
|
for (var i = 0; i < a.length; i += 1) {
|
|
|
|
arr[i] = a[i];
|
|
|
|
}
|
|
|
|
for (var j = 0; j < b.length; j += 1) {
|
|
|
|
arr[j + a.length] = b[j];
|
|
|
|
}
|
|
|
|
|
|
|
|
return arr;
|
|
|
|
};
|
|
|
|
|
|
|
|
var slicy = function slicy(arrLike, offset) {
|
|
|
|
var arr = [];
|
|
|
|
for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) {
|
|
|
|
arr[j] = arrLike[i];
|
|
|
|
}
|
|
|
|
return arr;
|
|
|
|
};
|
|
|
|
|
|
|
|
var joiny = function (arr, joiner) {
|
|
|
|
var str = '';
|
|
|
|
for (var i = 0; i < arr.length; i += 1) {
|
|
|
|
str += arr[i];
|
|
|
|
if (i + 1 < arr.length) {
|
|
|
|
str += joiner;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return str;
|
|
|
|
};
|
|
|
|
|
2023-07-29 20:33:28 +02:00
|
|
|
module.exports = function bind(that) {
|
|
|
|
var target = this;
|
2024-08-26 08:36:01 +02:00
|
|
|
if (typeof target !== 'function' || toStr.apply(target) !== funcType) {
|
2023-07-29 20:33:28 +02:00
|
|
|
throw new TypeError(ERROR_MESSAGE + target);
|
|
|
|
}
|
2024-08-26 08:36:01 +02:00
|
|
|
var args = slicy(arguments, 1);
|
2023-07-29 20:33:28 +02:00
|
|
|
|
|
|
|
var bound;
|
|
|
|
var binder = function () {
|
|
|
|
if (this instanceof bound) {
|
|
|
|
var result = target.apply(
|
|
|
|
this,
|
2024-08-26 08:36:01 +02:00
|
|
|
concatty(args, arguments)
|
2023-07-29 20:33:28 +02:00
|
|
|
);
|
|
|
|
if (Object(result) === result) {
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
return this;
|
|
|
|
}
|
2024-08-26 08:36:01 +02:00
|
|
|
return target.apply(
|
|
|
|
that,
|
|
|
|
concatty(args, arguments)
|
|
|
|
);
|
|
|
|
|
2023-07-29 20:33:28 +02:00
|
|
|
};
|
|
|
|
|
2024-08-26 08:36:01 +02:00
|
|
|
var boundLength = max(0, target.length - args.length);
|
2023-07-29 20:33:28 +02:00
|
|
|
var boundArgs = [];
|
|
|
|
for (var i = 0; i < boundLength; i++) {
|
2024-08-26 08:36:01 +02:00
|
|
|
boundArgs[i] = '$' + i;
|
2023-07-29 20:33:28 +02:00
|
|
|
}
|
|
|
|
|
2024-08-26 08:36:01 +02:00
|
|
|
bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder);
|
2023-07-29 20:33:28 +02:00
|
|
|
|
|
|
|
if (target.prototype) {
|
|
|
|
var Empty = function Empty() {};
|
|
|
|
Empty.prototype = target.prototype;
|
|
|
|
bound.prototype = new Empty();
|
|
|
|
Empty.prototype = null;
|
|
|
|
}
|
|
|
|
|
|
|
|
return bound;
|
|
|
|
};
|