JS面试点-new运算符的执行过程

2,594 阅读1分钟

Javascript中new对象的过程

// 创建构造函数
function People(name){
  this.name = name;
}

// 使用new创建实例对象person
var zxx = new People("ZXX");
zxx = {
  name: 'zxx'
}
代码执行过程
var obj = {} 或者 var obj = new Object() // 创建一个空对象;
obj.__proto__ = People.prototype // 将该隐式原型原型指向构造函数显式原型,建立对象和原型直接的对应关系。
People.call(obj, "ZXX") // 将构造函数中this指向创建的obj对象,并传入参数"ZXX"
return obj // 返回obj对象,person指向创建的obj对象(对象类型赋值为按引用传递,obj与person指向同一个对象)
相当于(IIFE
var person = function () {
    var obj = {}
    obj.__proto__ = People.prototype
    People.call(obj, 'ZXX')
    return obj
}() // 使用立即执行函数(IIFE)

模拟实现new方法

function newOperator(ctor, ...args) {
    if(typeof ctor !== 'function'){
      throw 'newOperator function the first param must be a function';
    }
    let obj = Object.create(ctor.prototype);
    let res = ctor.apply(obj, args);
    
    let isObject = typeof res === 'object' && res !== null;
    let isFunction = typoof res === 'function';
    return isObect || isFunction ? res : obj;
};