作者:
    作者:xl

    1. // call
    2. Function.prototype.myCall = function (context) {
    3. // 获取参数
    4. let args = [...arguments].slice(1);
    5. // 保存调用结果
    6. let result = null;
    7. // 判断 context 是否传入,如果未传入则设置为 window
    8. context = context || window;
    9. // 将函数设为对象的方法
    10. context.fn = this;
    11. // 调用函数
    12. result = context.fn(...args);
    13. // 属性删除
    14. delete context.fn;
    15. return result;
    16. }
    17. // apply
    18. Function.prototype.myApply = function (context) {
    19. let result = null;
    20. // 判断 context 是否传入,如果未传入则设置为 window
    21. context = context || window;
    22. // 将函数设为对象的方法
    23. context.fn = this;
    24. if (arguments[1]) {
    25. result = context.fn(...arguments[1]);
    26. } else {
    27. result = context.fn();
    28. }
    29. // 属性删除
    30. delete context.fn;
    31. return result;
    32. }

    作者:奥兰度

    1. function myCall(fn, thisArg, ...args) {
    2. if (typeof this !== "function") {
    3. console.log("type error");
    4. }
    5. let res;
    6. thisArg = thisArg || window;
    7. thisArg.fn = fn;
    8. result = thisArg.fn(...args);
    9. delete thisArg.fn;
    10. return result;
    11. };
    12. function myApply(fn, thisArg, argAry) {
    13. if (typeof this !== "function") {
    14. console.log("type error");
    15. }
    16. let res;
    17. thisArg = thisArg || window;
    18. thisArg.fn = fn;
    19. result = thisArg.fn(argAry);
    20. delete thisArg.fn;
    21. return result;
    22. };

    作者:
    作者:安静

    1. Function.prototype.myCall = function (context, ...args) {
    2. //这里默认不传就是给window,也可以用es6给参数设置默认参数
    3. context = context || window
    4. args = args ? args : []
    5. //给context新增一个独一无二的属性以免覆盖原有属性
    6. const key = Symbol()
    7. context[key] = this
    8. //通过隐式绑定的方式调用函数
    9. const result = context[key](...args)
    10. //删除添加的属性
    11. delete context[key]
    12. //返回函数调用的返回值
    13. return result
    14. }
    15. Function.prototype.myApply = function (context, array) {
    16. //这里默认不传就是给window,也可以用es6给参数设置默认参数
    17. context = context || window
    18. args = array ? array : []
    19. //给context新增一个独一无二的属性以免覆盖原有属性
    20. const key = Symbol()
    21. context[key] = this
    22. //通过隐式绑定的方式调用函数
    23. const result = context[key](...args)
    24. //删除添加的属性
    25. delete context[key]
    26. //返回函数调用的返回值
    27. return result
    28. }
    29. function a (...args) {
    30. console.log(args);
    31. console.log(this.name);
    32. }
    33. a.myApply({name: 'zhangsan'}, [1,2,3])

    作者:
    作者: