经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » JS/JS库/框架 » JavaScript » 查看文章
Javascript动手实现call,bind,apply的代码详解
来源:jb51  时间:2022/2/22 15:52:19  对本文有异议

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

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

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

4.获取传入的参数

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

6.将对象上的fn删除

7.返回结果

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

总结

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

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号