call 允许一个函数在另一个对象的上下文中执行,也就是说你可以借用一个函数,并临时将它的 this 指向任意对象。
call allows a function to be executed in the context of a different object, meaning you can borrow a function and temporarily point its this to any object you want.
apply 和 call 作用完全相同,都是借用函数并临时将 this 指向任意对象。唯一的区别是参数传递方式:apply 要求把所有参数放进一个数组里传入。
apply does exactly the same thing as call. It borrows a function and temporarily points its this to any object you want. The only difference is how arguments are passed: apply requires all arguments to be packed into an array.
bind 和 call/apply 的作用相同,都是将函数的 this 绑定到指定对象上。区别在于 bind 不会立即执行函数,而是返回一个永久绑定了 this 的新函数,让你在任何时候调用它,this 都不会丢失。
bind does the same thing as call/apply. It ties a function’s this to a specific object. The difference is that bind doesn’t execute the function immediately. Instead, it returns a new function with this permanently locked in, so no matter when or where you call it, this will never be lost.
Function.prototype.myBind = function (context, ...args1) { const fn = this; functionboundFunction(...args2) { // if it is new called if (thisinstanceof boundFunction) { returnnewfn(...args1, ...args2); } return fn.apply(context, [...args1, ...args2]); } // maintain the prototype chain boundFunction.prototype = Object.create(fn.prototype); return boundFunction; };
functionfoo(a, b) { console.log(this.name); return a + b; } const obj = { name: "obj" }; // bind will not execute immediately, it will return a new function const boundFoo = foo.myBind(obj, 1); const result = boundFoo(2); // obj console.log(result); // 3