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');

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注0133技术站的更多内容!  

以上就是Javascript动手实现call,bind,apply的代码详解的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » JavaScript 教程