做个总结贴。
- call/apply/bind
Function.prototype.apply = function (obj, args) {
// 参数处理
if (!obj) obj = window;
else obj = Object(obj);
args = Array.from(args);
// 绑定this
const testFn = Symbol('testFn');
obj[testFn] = this;
let res = obj[testFn](...args);
delete obj[testFn];
return res;
}
Function.prototype.call = function (obj, ...args) {
// 参数处理
if (!obj) obj = window;
else obj = Object(obj);
// 绑定this
const testFn = Symbol('testFn');
obj[testFn] = this;
let res = obj[testFn](...args);
delete obj[testFn];
return res;
}
Function.prototype.bind = function (obj) {
// 参数处理
if (!obj) obj = window;
else obj = Object(obj);
let that = this; // 保存函数
// 通过闭包,进行临时绑定
return function (...args) {
const testFn = Symbol('testFn');
obj[testFn] = that;
let res = obj[testFn](...args);
delete obj[testFn];
return res;
}
}
// test call/apply/bind
function fn(a) {
console.log(a + this.b);
}
fn.apply({ b: 3 }, [5]);
fn.call({ b: 3 }, 4);
let add = fn.bind({ b: 9 });
add(8);
add(9)
2.new
function mynew(func, args) {
// 构造函数 参数数组
if (func && typeof func !== 'function') {
return {}; // 或者 throw error
}
let child = {};
child.__proto__ = func.prototype;
func.apply(child, args);
return child;
}
function A(a = -5) {
this.a = a;
this.b = 5;
}
A.prototype.add = function () {
console.log(this.a + this.b)
}
let a = mynew(A, [5]);
a.add()
let b = mynew(A);
b.add()
补充部分
关于bind的参数添加可以通过闭包实现,类似柯里化。