globalThis
call
参数是一个一个的传递
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/call
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;}
use
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
参数是个数组
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/apply
// apply 改变函数的 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;}
bind
创建一个新函数,并返回这个新函数,
不会执行这个函数,只是返回新函数,需要手动执行
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
export function bind(func, object, ...args) {if(object == null) {object = globalThis; // es11中的全局对象}// bind 返回一个新函数,调用目标函数,改变其 this指向return (...args2) => {return func.call(object, ...args, ...args2);}}
use
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)
