call apply bind 使用

call apply bind , 均是用于改变函数调用时 this 指向,第一个参数都是 this 指向的对象, callapply 调用就立即执行函数, call 第二参数开始是具体参数,apply 第二参数数组, bind 调用时可以传参并且返回一个函数,返回的函数调用时也可以传参。

  1. fun.call(thisArg, param1, param2, ...)
  2. fun.apply(thisArg, [param1, param2, ...])
  3. fun.bind(thisArg, param1, param2, ...)
  4. const obj = {
  5. a: '1'
  6. }
  7. function zz(a, b) {
  8. console.log(this, a, b);
  9. }
  10. zz.apply(obj, [1, 2]) //{a: '1'} 1 2
  11. zz.call(obj, 1, 2) //{a: '1'} 1 2
  12. zz.bind(obj, 1, 2)() //{a: '1'} 1 2

apply 实现

利用改变 this 指向的特性

  1. function zz(a, b) {
  2. console.log(this, a, b);
  3. }
  4. let obj = {
  5. a: '1'
  6. }
  7. Function.prototype.myapply = function(context) {
  8. context = context || window
  9. let args = [...arguments].slice(1)[0] || [];
  10. context.originFn = this;
  11. const result = context.originFn(...args)
  12. delete context.originFn;
  13. return result;
  14. }
  15. zz.myapply(obj, [1, 3]) //{ a: '1'} 1 3

call 实现

  1. Function.prototype.mycall = function(context) {
  2. context = context || window
  3. const args = [...arguments].slice(1);
  4. const that = this;
  5. return that.myapply(context, args)
  6. }
  7. zz.mycall(obj, 1, 5) ////{ a: '1'} 1 5

bind 实现

  1. Function.prototype.mybind = function(context) {
  2. if (typeof this !== 'function') {
  3. throw new TypeError('Error');
  4. }
  5. const that = this;
  6. const args = [...arguments].slice(1);
  7. return function newFn() {
  8. if (this instanceof newFn) {
  9. return new that(...args, ...arguments);
  10. }
  11. return that.myapply(context, args.concat(...arguments));
  12. }
  13. }
  14. let yy = zz.mybind(obj)
  15. yy(1, 2) // { a: '1'} 1 2