温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Javascript实现call,bind,apply的代码怎么写

发布时间:2022-02-22 13:38:27 来源:亿速云 阅读:183 作者:iii 栏目:开发技术

这篇文章主要介绍了Javascript实现call,bind,apply的代码怎么写的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇Javascript实现call,bind,apply的代码怎么写文章都会有所收获,下面我们一起来看看吧。

1.检查当前调用的是否为函数

2.如果当前没有传入指向的this,则赋值为window

3.将fn指向当前调用的函数

4.获取传入的参数

5.将参数传入fn进行调用

6.将对象上的fn删除

7.返回结果

  //普通call的实现   function hello(){       console.log('hello 我是'+this.name);   };   let person = {       name:'krys'   };   var name = 'liang';//只有var的变量属于window   hello();// 'hello 我是liang'   hello.call(person);//'hello 我是krys'   hello.call();//'hello 我是liang'   let person2 = {       name:'lwl'   }   Function.prototype.mycall = function(context){       //不传入参数的时候,默认为window       if(typeof this !== "function"){           throw new TypeError('Error');       }       context = context || window;       context.fn = this;//fn就是上面的hello方法       const args = [...arguments].slice(1);//第一个参数不要       const result = context.fn(...args);//把剩下的其他参数传给hello       delete context.fn;       return result;   }   hello.mycall(person2);
function getParams(){         console.log('我是',this.name,'获取一些参数',...arguments);     }     let person3 = {         name:'hhh'     };     getParams.apply(person3,['hello','world'])     Function.prototype.myApply = function(context){         if(typeof this !== "function"){             throw new TypeError()         }         context = context || window;         context.fn = this;         let result;         if(arguments[1]){             //如果有传入参数数组             console.log(arguments[1])             result  = context.fn(...arguments[1]);         }else{             result  = context.fn();         }         delete context.fn;         return result;     }     getParams.myApply({name:'llll'},['jjj','kkkk','llll']);
function getParams(){         console.log('我是',this.name,'获取一些参数',...arguments);     }     let person3 = {         name:'hhh'     };     let person4 = {         name:'tttt'     };     getParams.bind(person3,'hello','world')     getParams.bind(person4,'hello','world')('jjj','kkk');     Function.prototype.myBind = function(context){         if(typeof this !== "function"){             throw new TypeError()         }         context = context || window;         const _that = this;         const args = [...arguments].slice(1);         return function F(){             if(this instanceof F){                 return new _that(...args,...arguments);//这里的arguments是上面的jjj kkk             }             return _that.apply(context,args.concat(...arguments));//这里的arguments是上面的jjj kkk         }     }     getParams.myBind({name:'llll'},'jjj','kkkk','llll')('hhhhllll');

关于“Javascript实现call,bind,apply的代码怎么写”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“Javascript实现call,bind,apply的代码怎么写”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI