美文网首页
javascript面试基础

javascript面试基础

作者: 阡陌昏晨 | 来源:发表于2023-09-10 16:13 被阅读0次

    1、this call apply bind
    一个例子理解 call apply bind 都是为了改变this指向的问题

      function sayHello(para){
            console.log(`${para} ${this.name}`)
          }
    
          person={
            name:'zdq'
          }
          sayHello.call(person,'hello','world')
    
          sayHello.apply(person,['hi'])
    
          const newSayHello= sayHello.bind(person)
          newSayHello('hh')
    

    自定义call

     Function.prototype.myCall=function(context){
            const fn =this;
            context.fn=fn
            const args = Array.from(arguments).slice(1);
           const result= context.fn(...args)
           delete context.fn
           return result
          }
          sayHello.myCall(person,'自定义call')
    

    //自定义实现一个apply

          Function.prototype.myApply=function(context,args){
          console.log('myApply',args)  
          const fn =this;
          context.fn=fn
          const result=context.fn(...args)
          delete context.fn
           return result
          }
    
     //手写bind函数
          Function.prototype.myBind=function(context){
            const fn=this;
            console.log('myBind',arguments)
            let args = Array.from(arguments).slice(1); //
            console.log('myBind',args)
            return function(){
                const newArr=args.concat(Array.from(arguments))
                fn.apply(context,newArr)
                console.log('myBind newArr',newArr)
                // fn.apply(context,args)
            }
          }
            // 声明一个函数
        function fn(a, b, c) {
            console.log("函数内部this指向:", this);
            console.log("参数列表:", a, b, c);
        }
        const newFun=fn.myBind({},10,20,30)
        newFun(40)
    

    相关文章

      网友评论

          本文标题:javascript面试基础

          本文链接:https://www.haomeiwen.com/subject/rypsvdtx.html