bind
bind() 预先处理机制
export function bind(func, object, ...args) {if(object == null) {object = globalThis; // es11中的全局对象}// bind 返回一个新函数,调用目标函数,改变其 this指向return (...args2) => {return func.call(object, ...args, ...args2);}}function add(a,b) {console.log(this);return a + b + this.c;}const obj = { c: 100 }window.c = 200;const fn = bind(add, obj, 10, 20);const fn2 = bind(add, obj);fn2(100, 200)
call
call改变函数的 this指向
export function call(func, object, ...args) {if(object == null) {object = globalThis; // es11中的全局对象}// 添加临时方法object.temp = func;const result = object.temp(...args);delete object.temp;return result;}function add(a,b) {console.log(this);return a + b + this.c;}const obj = { c: 100 }window.c = 200;call(add, obj, 10, 20);call(add, null, 10, 20)
apply
apply 改变函数的 this指向, []
export function apply(func, object, args) {if(object == null) {object = globalThis; // es11中的全局对象}// 添加临时方法object.temp = func;const result = object.temp(...args);delete object.temp;return result;}function add(a,b) {console.log(this);return a + b + this.c;}const obj = { c: 100 }window.c = 200;apply(add, obj, [10, 20]);apply(add, null, [10, 20])
