js-面试,手写代码系列:bind,call,apply,new
bind
Function.prototype._bind = function (thisArg, ...rest) {
if (typeof thisArg === 'undefined') thisArg = window || global
thisArg.fn = this;
return function () {
const res = thisArg.fn(...rest);
delete thisArg.fn
return res;
}
}
call
Function.prototype._call = function (thisArg, ...rest) {
if (typeof thisArg === 'undefined') thisArg = window || global;
thisArg.fn = this;
const res = thisArg.fn(...rest);
delete thisArg.fn
return res;
}
apply
Function.prototype._apply = function (thisArg, rest) {
if (typeof thisArg === 'undefined') thisArg = window || global;
thisArg.fn = this;
const res = thisArg.fn(...rest);
delete thisArg.fn
return res;
}
new
function _new(constructor, ...rest) {
const instance = {};
instance.__proto__ = constructor.prototype;
// 处理构造函数对应的this
const res = constructor.apply(instance, rest);
if (typeof res === 'object' || typeof res === 'function') return res;
return instance;
}
function P() {
this.a = '1'
}
P.prototype.a = '1'
const p1 = _new(P);
console.log(p1 instanceof P); // true
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 kshao-blog-前端知识记录!
评论