We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
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的模拟实现
The text was updated successfully, but these errors were encountered:
No branches or pull requests
前言
call/apply/bind 都是改变this指向的方法;
其中call/bind的形参都是 newFun.call(obj,param1,param2)
而apply的形参则是 newFun.apply(obj,[param1,param2])
执行上,call/apply是立即执行但没有返回,而bind则不立即执行并返回可执行函数,相当于预制菜,加热即可使用。
看段代码
含义
如上代码可以看出,call的作用是改变函数内部的this,那我们开始改造
call2方法的this会指向调用call2的函数;
既然this指向搞定了,那就开始处理 参数了;
形参用 arguments
以上就是大致思路:1. 把调用call的函数变成目标this指向的对象的fn,执行fn再删除;2. 参数处理用 函数的内部属性 arguments (形参实参数组);
下一篇文章
JavaScript深入之new的模拟实现
The text was updated successfully, but these errors were encountered: