请教一下手写call,请老师指点一二
来源:6-5 作用域相关的面试题 - part1

慕丝7210068
2020-05-14
思路:
首先明确这三个方法是Function 原型上的三个方法 也就是说你需要是一个函数才能调用 也就是你得在Function原型上来完成
这道题目,并且调用方需是一个函数
- call 这个函数的意思是假设你有一个foo函数, 然后调用foo这个函数上的call方法,传递进入多个参数,
- 第一个参数假设名字叫A 是你期望更改的foo内部的this指向的对象,其他参数假设名字叫B,C,D 作为foo的参数传入
- 返回值是调用 foo函数,并将foo中的this指向A ,并且返回foo的结果,类似于调用了
A.foo()
function foo(a,b){
console.log(this)
console.log(a,b)
}
var obj = {
name:'this is new this',
}
Function.prototype.myCall = function(){
// 如何不使用函数的apply call bind 实现?
var args = [];
for (var i = 1; i < arguments.length; i++) {
args.push(arguments[i]);
}
console.log(args)
// 这种取函数名的方法可取吗?
let functionName = this.name;
let newThis = arguments[0];
newThis[functionName] = this;
// 如何不使用展开运算符?
return newThis[functionName](...args)
}
foo.myCall(obj,10,20)
待完成apply bind,请老师指教,最好不要用到js已有的apply bind call 这三个方法
写回答
1回答
-
双越
2020-05-15
let newThis = arguments[0]; newThis[functionName] = this; // 如何不使用展开运算符? return newThis[functionName](...args) // 以上这几行,能不能直接改为下面这一行? return this[...args]
10
相似问题