-
Notifications
You must be signed in to change notification settings - Fork 292
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
第 6 题:手写代码,简单实现call #6
Comments
为什么用 eval 执行?下面的方式,不是更方便? Function.prototype.call2 = function(context, ...args) {
// 因为传进来的 context 有可能是 null
context = context || window;
// Function.prototype this 为当前运行的函数
// 让 fn 的上下文为 context
context.fn = this;
const result = context.fn(...args);
delete context.fn;
return result;
};
function test(a, b, c) {
console.log(this, a, b, c);
return this;
}
test.call2({ test: 22 }, 1, 2, 3); |
同问,想请教下为什么在这里要采用eval的形式来执行函数? |
@jinggk 他这个是 es5 时代的写法,不支持 es6 之前没有 |
@xianshannan @jinggk 是的 这题的最重要考点是this的指向性问题 使用eval固然性能不好 但是兼容性好 并且能达到实现本题的效果 但是用es6也是一个不错的方法 但是真正的call和apply可比这复杂得多 欢迎各种答案和想法交流 |
嗯 试了一下 如果不用这种形式好像避不开 Array.prototype.slice.call(arguments) 这个问题 |
Function.prototype.call2 = function() { var test = function(a, b) {console.log(a, b);} test.call2({}, 1, 2); |
严格模式下 怎么处理 this 为null的情况? |
The text was updated successfully, but these errors were encountered: