JavaScript-new的实现原理

99 阅读1分钟
  • 创建一个空对象,构造函数中的this指向这个空对象
  • 这个新对象被执行 原型 连接
  • 执行构造函数方法,属性和方法被添加到this引用的对象中
  • 如果构造函数中没有返回其它对象,那么返回this,即创建的这个的新对象,否则,返回构造函数中返回的对象。
function _new() {
    // 创建一个空对象
    let target = {};
    // constructor为构造函数
    let [constructor, ...args] = [...arguments];
    // 执行 原型 连接,target是constructor的实例
    target.__proto__ = constructor.prototype;
    // 将constructor的this改变为target的this,并且把args传入进去(当作传参看待)
    let result = constructor.apply(target, args);
    // 构造函数返回对象
    if (result && typeof (result == 'object' || typeof result == 'function')) {
        return result;
    }
    return target;
}
let getAge = function(age) {
    return {
        name: 'sql',
        log: function() {
            console.log(age);
        }
    };
};
getAge.prototype.prot = 'prot';
let age = _new(getAge, 18);
age.log(); // 18