new 实例化原理

88 阅读1分钟

1、new之后会生成一个空对象

2、该对象的原型对象(obj. proto = object.prototype)会指向构造函数的原型属性,从而继承原型上的方法

3、this指向该构造函数,以获取其私有属性

4、如果该构造函数返回了res对象/函数,就将res返回,否则返回空对象

手动实现new

es5写法
function _new (target) {
    var obj = {}
    params = [].splice.call(arguments,1)  ====argument.splice(0,1)
    result
    
    obj.__proto__ = target.prototype
    result = target.apply(obj.params)
    if (result != null && /^(function|object)$/.test(typeof result)) {
        return result
    } 
    return obj
    
    

}

===================================================
es6写法
function _new(target,...params) {
    let obj = Object.create(target.prototype),
    result = target.call(obj,...params)
    if (result != null && /^(function|object)$/.test(typeof result)) {
        return result
    } 
    return obj
}