Function.prototype.bind
bind
bind()方法创建一个新的函数,在bind()被调用时,这个新函数的this被指定为bind()的第一个参数,而其余参数将作为新函数的参数,供调用时使用。MDN
function fn() {
console.log("[console value]", this.value);
}
const obj = {
value: "this is obj.value",
};
const bindFn = fn.bind(obj);
bindFn() // [console value] this is obj.value
bindSimply
Function.prototype.bindSimply = function (obj) {
const fn = this;
return function () {
fn.call(obj);
};
};
const bindSM = fn.bindSimply(obj);
bindSM() // [console value] this is obj.value
✅ 没问题
arguments
fn = function fn(arg1, arg2) {
console.log("[console value]", this.value);
console.log("[console arg1]", arg1);
console.log("[console arg2]", arg2);
}
Function.prototype.bindSimply = function (obj) {
const fn = this;
return function () {
fn.call(obj, ...arguments);
};
};
const bindSMMen = fn.bindSimply(obj);
bindSMMen("gay1", "gay2");
// [console value] this is obj.value
// [console arg1] gay1
// [console arg2] gay2
Currying
Function.prototype.bindSimply = function (obj, ...args) {
const fn = this;
return function () {
fn.call(obj, ...args, ...arguments);
};
};
fn = function fn() {
console.log("[console value]", this.value);
console.log("[console arguments]", arguments);
};
const bindSMMenMen = fn.bindSimply(obj, "gay3", "gay4");
bindSMMenMen("gay1", "gay2");
// [console value] this is obj.value
// [console arguments] [Arguments] { '0': 'gay3', '1': 'gay4', '2': 'gay1', '3': 'gay2' }
new
Function.prototype.bindSimply = function (obj, ...args) {
const fn = this;
return function () {
if (new.target) return new fn(...arg, ...arguments);
fn.call(obj, ...args, ...arguments);
};
};
prototype
Function.prototype.bindSimply = function (obj, ...args) {
const fn = this;
function res() {
if (new.target) return new fn(...arg, ...arguments);
fn.call(obj, ...args, ...arguments);
}
res.prototype = undefined;
return res;
};
const bindSMNoeye = fn.bindSimply(obj);
bindSMNoeye.prototype