zxdfe / FE-Interview

Every step counts
34 stars 1 forks source link

第23题:new的执行过程?手写一个new? #23

Open zxdfe opened 1 year ago

naVuppe commented 1 year ago
  1. 创建一个空对象
  2. this指向这个空对象
  3. 执行构造函数代码,给this添加属性和方法
  4. 把this作为返回值返回
    function Qwer(name){
        this.name = name;
        this.age = 18;
        this.fn = function(){
            console.log(this.name);
        }
    }
    const qwe = new Qwer('pink');
    qwe.fn();
zxdfe commented 1 year ago
  1. 创建一个空对象
  2. this指向这个空对象
  3. 执行构造函数代码,给this添加属性和方法
  4. 把this作为返回值返回
    function Qwer(name){
        this.name = name;
        this.age = 18;
        this.fn = function(){
            console.log(this.name);
        }
    }
    const qwe = new Qwer('pink');
    qwe.fn();

手写new不是指的这个哈

A-Lonely-GEEK commented 1 year ago
    function myNew(fn, ...args) {
        let obj = new Object()
        obj.__proto__ = fn.prototype

        let res = fn.call(obj, ...args)

        if (res && (typeof res === 'object' || typeof res === 'function')) return res
        else return obj
    }
szgyFE commented 1 year ago

手写一个new是直接用原型继承吗??

ttizzyf commented 1 year ago

1、创建一个空对象 2、构造函数中的this指向这个对象 3、执行构造函数,给空对象赋值 4、返回这个对象