面试中常被考到的手撕代码:
- call/apply/bind
- instanceof
- 深拷贝
- 基于 ES5/ES6 实现“双向绑定”
- promise相关
1. call/apply/bind的代码实现
call
Function.prototype.call2 = function(context) {
if (typeof this !== "function") {
throw new TypeError("Error");
}
// 默认上下文是window
context = context || window;
// 保存默认的fn
const {
fn } = context;
// 将函数本身作为对象context的属性调用,自动绑定this
context.fn = this;
const args = [...arguments].slice(1);
const result = context.fn(...args);
// 恢复默认的fn
context.fn = fn;
return result;
};
apply
Function.prototype.apply2 = function(context) {
if (typeof this !== "function") {
throw new TypeError("Error");
}
context = context || window;
const {
fn } = context;
context.fn = this;
let result;
if (Array.isArray(arguments[1])) {
// 通过...运算符将数组转换为用逗号分隔的参数序列
result = context.fn(...arguments[1]);
} else {
result = context.fn();
}
context.fn = fn;
return result;
};
bind
Function.prototype.bind2 = function(context