new操作符做了什么?手写一个new

1,680 阅读1分钟

new操作符的常规操作

function User() {
    this.name = 'xiaoming';
    this.age = 20;
}

const user = new User();
console.log(user);// {name: "xiaoming", age: 20}

通过以上的操作,我们就可以得到一个name为'xiaoming', age为20实例对象

new操作符做了什么

  • 先创建了一个空的对象
const obj = {};
// or
const obj = new Object();
  • 链接该对象到另一个对象上(将该对象的_proto_指向构造函数的的prototype)
obj._proto_ = User.prototype;
  • 把创建的obj作为this的上下文

  • 判断构造函数的返回值

返回为值类型(return 1;): 丢弃这个值,则返回obj;
返回为引用类型(return {name: 'hahah'}): 则返回这个引用类型
{
    若没有返回(没有return), 相当于 return undefined, undefined是值类型,则相当于返回obj
    若返回thisreturn this),由第三条可知,this的上下文是obj,所以相当于返回obj
}

完整的手写new

function myNew (Constr, ...args) {
    // 创建对象
    const obj = {};
    // 链接对象
    obj._proto_ = Constr.prototype;
    // 绑定this
    let res = Constr.call(obj, ...args);
    // 判断返回类型
    return res instanceof Object ? res : obj;
}

检验

    function User(name, age) {
        this.name = name;
        this.age = age;
        return function aa() {
            console.log('qq')
        }
    }
    function myNew (Constr, ...args) {
        // 创建对象
        const obj = {};
        // 链接对象
        obj._proto_ = Constr.prototype;
        // 绑定this
        const res = Constr.call(obj, ...args);
        // 判断返回类型
        return res instanceof Object ? res : obj;
    }
    const user = myNew(User, 'momo', 20);
    console.log(user);

	function User(name, age) {
        this.name = name;
        this.age = age;
    }
    function myNew (Constr, ...args) {
        // 创建对象
        const obj = {};
        // 链接对象
        obj._proto_ = Constr.prototype;
        // 绑定this
        const res = Constr.call(obj, ...args);
        // 判断返回类型
        return res instanceof Object ? res : obj;
    }
    const user = myNew(User, 'momo', 20);
    console.log(user);