new操作符做了什么事?

120 阅读1分钟

new操作符大家都不陌生,平常也经常使用到,但是new如何实现的呢?

1.声明一个空对象。

let obj = {};

2.更改obj.__proto__指向

var Con = [].shift.call(arguments);
obj.__proto__ = Con.prototype;

3.更改this指向

Con,apply(obj,arguments);

4.返回obj

return obj;

示例

function Person(name,age){
    this.name = name;
    this.age = age;
}
function NewFunction(){
    let obj = {};
    let Con = [].shift.call(arguments);
    obj.__proto__ = Con.prototype;
    Con.apply(obj,arguments);
    return obj;
}
let person1 = NewFunction(Person,'Nerd_C',22);
console.log(person1.name)
//Nerd_C
console.log(person1.age)
//22