手写 new

113 阅读1分钟

new操作符三步曲:

① 创建了一个实例对象

② 函数执行,在函数的私有执行上下文中的this指向这个实例对象

③ 返回值:没有或者基本数据类型值,则返回这个实例对象


手写 new 原理,将三部曲翻译成代码:

new 操作符

每一个对象数据类型值,天生自带一个属性__proto__原型链属性(隐式原型),属性值指向所属类的原型对象prototype

function Cat(name){
    this.name = name;
}
Cat.prototype.say = function (){
    console.log('miaomiao~'+this.name);
};
let c1 = new Cat('Tom');
c1.say();                           // 'miaomiao~Tom'
console.log(c1 instanceof Cat);     // true

// 实现_new函数
let c2 = _new(Cat, 'Kitty');
c2.say();                            // 'miaomiao~Kitty'
console.log(c2 instanceof Cat);      // true

手写new原理

function _new(Ctor, ...args){
    // 1. 创建一个实例对象【实例.__proto__ => 所属类的原型 Ctor.prototype】
    let obj = Object.create(Ctor.prototype);
    
    // 2. 函数执行,并让私有执行上下文中的this指向这个实例对象
    let result = Ctor.call(obj, ...args);
    
    // 3. 返回值:没有或者基本数据类型值,则返回这个实例对象
    if(result !== null && /^(object|function)$/.test(typeof result)){
        return result;
    }
    return obj;
}