尝试自己写个 new

94 阅读1分钟

先丢代码,后面补知识点 new 执行的时候做了啥? new 执行函数与普通函数执行有啥区别? new 执行优先级问题 自己写个new方法

function Person(name, age, sex) {
    this.name = name;
    this.age = age;
    this.sex = sex;
    this.sayHi = function () {
        alert('我的名字叫:' + this.name + ',年龄:' + this.age + ',性别:' + this.sex);
    }
    return 12222
}

const _new = function _new(Ctor, ...params) {
    if (typeof Ctor !== "function" || !Ctor.prototype || Ctor === Symbol || Ctor === BigInt) new TypeError(`${Ctor} is not a constructor!`);
    let obj,
        result;
    obj = Object.create(Ctor.prototype);
    result = Ctor.call(obj, ...params);
    if (Ctor === Number || String || Boolean) result = Object(result);
    if (result !== null && /^(object|function)$/i.test(typeof result)) return result;
    return obj;
}

console.log(_new(Number, 10));
console.log(_new(Boolean, null));
console.log(_new(String, 'straaa'));
console.log(_new(Array, 1 ,2, 3));
// 自定义的
console.log(_new(Person, 'ss', 18, '女'));

// let obj1 ;
// obj1 = Number.call(obj1,100);
// console.log(obj1);