手写函数

67 阅读1分钟

手写new函数

function _new() {
   // 创建一个对象
    const obj = new Object();
    // 取出构造函数
    const [constructor, args] = [...arguments];
    //对象的原型等于构造函数的原型
    obj.__proto__ = constructor.prototype;
    // 对象可以访问构造函数的属性
    const ret = constructor.apply(obj, args);
    // 返回一个对象
    // return obj; 如果对象返回的基本类型则忽略,如果返回的是对象,直接返回实例对象
    return typeof ret === 'object' ? ret : obj;  
}

手写bind函数

Function.prototype.mybind = function(context) {
    //判断this
    if(typeof this !== 'function'){
        throw new TypeError('类型错误');
    }
    const fn = this;
    const args = [...arguments].slice(1);
    return  function Fn() {
        const that =  this instanceof Fn ?  new Fn(...arguments) : context;
       fn.apply(that, args.concat(...arguments));
    }
}

手写call 函数

Function.prototype.mycall = function(context) {
    if(typeof this !== 'function') {
        throw new TypeError('类型错误');
    }
    context = context || window;
    context.fn = this;
    const args = [...arguments].slice(1);
    const result = context.fn(...args);
    delete context.fn;
    return result;
}

手写 apply 函数

Function.prototype.myapply = function(context) {
    if(typeof this !== 'function') {
        throw new TypeError('类型错误');
    }
    context = context || window;
    context.fn = this;
    const result;
    if(arguments[1]){
        result = context.fn(...arguments[1]);
    }else {
        result  = context.fn();
    }
    delete context.fn;
    return result;
}