js中手写apply(不能使用ES6语法)和使用ES6语法对比

js手写apply(不能使用ES6语法)

参考前边手写call

// apply和call的区别就是传参方式不同,apply第二个参数传的是数组
        Function.prototype.myApply = function(context,args){
                if(context === null || context === undefined){
                    context = window
                }else{
                    context = Object(context)
                }
            function mySymbol(obj){
                let unique = Math.random() + new Date().getTime()
                if(obj.hasOwnProperty(unique)){
                    return mySymbol(obj)
                }else{
                    return unique
                }
            }
            let fnName = mySymbol(context)
            context[fnName] = this
            let arr = []
            if(args){
                for (let i = 0; i <args.length; i++) {
                    arr.push('args[' + i + ']')
                }
            }
            let result = eval('context[fnName]('+arr.join(',')+')')
            delete context[fnName]
            return result
        }

js手写apply(使用ES6语法)

		Function.prototype.myApply = function(context,args){
            if(context === null || context === undefined){
                context = window
            }else{
                context = Object(context)
            }
            let fnName = Symbol('唯一')
            context[fnName] = this
            let result = context[fnName](...args)
            delete context[fnName]
            return result
        }

你可能感兴趣的:(JavaScript)