Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JavaScript深入之call和apply的模拟实现 #10

Open
huiyiwanan opened this issue Jan 16, 2023 · 0 comments
Open

JavaScript深入之call和apply的模拟实现 #10

huiyiwanan opened this issue Jan 16, 2023 · 0 comments
Labels
Javascript 深入系列 Improvements or additions to documentation

Comments

@huiyiwanan
Copy link
Owner

huiyiwanan commented Jan 16, 2023

前言

call/apply/bind 都是改变this指向的方法;
其中call/bind的形参都是 newFun.call(obj,param1,param2)
而apply的形参则是 newFun.apply(obj,[param1,param2])
执行上,call/apply是立即执行但没有返回,而bind则不立即执行并返回可执行函数,相当于预制菜,加热即可使用。

看段代码

function foo(){
    console.log(this.name);
}
const a = {name:'Kervin'}
this.name = 'aa'
foo()//'aa'
foo.call(a) //Kervin

含义

如上代码可以看出,call的作用是改变函数内部的this,那我们开始改造

Function.prototype.call2 = function(obj){
    console.log();
    obj.fn = this;
    obj.fn();
    delete obj.fn;
}
function foo() {
    console.log(this.name)
}
foo.call2({name:'21'})

call2方法的this会指向调用call2的函数;
既然this指向搞定了,那就开始处理 参数了;
形参用 arguments

Function.prototype.call2 = function(obj){
    obj.fn = this;
    console.log(arguments);
    console.log(arguments[0],arguments[1]);
    const arr = arguments || [];
    let str = '';
    for(let i=1; i< arr.length; i++){
       str += arr[i] + ','
    }
    console.log(str)
    eval('obj.fn(' + str + ')')
    delete obj.fn;
}
function foo(a,b) {
    console.log(this.name);
    console.log(a);
    console.log(b)
}
foo.call2({name:'21'},'a','b')

以上就是大致思路:1. 把调用call的函数变成目标this指向的对象的fn,执行fn再删除;2. 参数处理用 函数的内部属性 arguments (形参实参数组);

下一篇文章

JavaScript深入之new的模拟实现

@huiyiwanan huiyiwanan added the Javascript 深入系列 Improvements or additions to documentation label Jan 16, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Javascript 深入系列 Improvements or additions to documentation
Projects
None yet
Development

No branches or pull requests

1 participant