手写call方法

javascript 复制代码
 Function.prototype.myCall=function (context,args) {
        console.log(arguments)
        //context 表示call里面的第一个参数也就是需要改变this指向的那个对象。
        //this表示这个方法
        //把这个方法挂到需要改变指向的对象身上调用,相当于把this指向了这个对象身上,从而达到改变this的作用。
        //argument是一个特殊的对象,可以获取方法传入的参数。
        context.fn=this
        let arr = []
        for(let i =1;i<arguments.length;i++){
            console.log(arguments[i])
            
                //arr.push(arguments[i])
                arr.push('arguments[' + i + ']');
           
        }
        console.log(arr)
        console.log(arguments[1])
        eval('context.fn('+arr+')')
        //context.fn();
        delete context.fn

    }


    let person = {
        name:'tom',
        age:22,
        sex:'male',
        sayName:function(){
            console.log(this.name)
        },
        showInfo:function(name,age,sex){
            this.name=name;
            this.age=age;
            this.sex=sex;
            console.log('name:'+this.name+',age:'+this.age+',sex:'+this.sex)
        }
    }

    let person2={
        name:'tony'
    }
    person.showInfo('lily',22,'female')
    person.showInfo.myCall(person2,'john',11,'male') //name:john,age:11,sex:male
相关推荐
liuyao_xianhui33 分钟前
优选算法_最小基因变化_bfs_C++
java·开发语言·数据结构·c++·算法·哈希算法·宽度优先
做一个AK梦35 分钟前
计算机系统概论知识点(软件设计师)
java·开发语言
東雪木1 小时前
Java学习——一访问修饰符(public/protected/default/private)的权限控制本质
java·开发语言·学习·java面试
cch89181 小时前
易语言与C++:编程语言终极对决
开发语言·c++
shark22222221 小时前
Python 爬虫实战案例 - 获取社交平台事件热度并进行影响分析
开发语言·爬虫·python
551只玄猫2 小时前
【数学建模 matlab 实验报告6】行遍性问题
开发语言·数学建模·matlab
程序员小寒2 小时前
JavaScript设计模式(八):命令模式实现与应用
前端·javascript·设计模式·ecmascript·命令模式
wgod2 小时前
new AbortController()
前端
UXbot2 小时前
UXbot 是什么?一句指令生成完整应用的 AI 工具
前端·ai·交互·个人开发·ai编程·原型模式·ux
棒棒的唐2 小时前
WSL2用npm安装的openclaw,无法正常使用openclaw gateway start启动服务的问题
前端·npm·gateway