使用ES6

    1. Function.prototype.call2 = function (context, ...args) {
    2. /// ...args 把剩余的参数都放到数组里面
    3. var context = context || window
    4. const fn = Symbol();
    5. context.fn = this
    6. let result = context.fn(...args)
    7. delete context.fn
    8. return result
    9. }
    1. Function.prototype.apply2 = function (context, arr) {
    2. context = context || window
    3. const fn = Symbol();
    4. context.fn = this
    5. let result = context.fn(...arr)
    6. delete context.fn
    7. return result
    8. }

    不使用ES6

    1. Function.prototype.call2 = function (context) {
    2. context = context || window
    3. context.fn = this
    4. let args = []
    5. for (let i = 1, len = arguments.length; i < len; i++) {
    6. args.push('arguments['+i+']')
    7. }
    8. //这里使用eval,args 会自动调用 Array.toString() 这个方法。
    9. let result = eval('context.fn('+args+')')
    10. delete context.fn
    11. return result
    12. }
    1. Function.prototype.apply2 = function (context, arr) {
    2. context = context || window
    3. context.fn = this
    4. let result
    5. if (!arr) {
    6. result = context.fn()
    7. } else {
    8. let args = []
    9. for (let i = 0, len = arr.length; i < len; i++) {
    10. args.push('arr[' + i + ']')
    11. }
    12. result = eval('context.fn(' + args + ')')
    13. }
    14. delete context.fn
    15. return result
    16. }