javascript中在new一个对象时发生了什么?
1.创建一个新对象
2.将新对象的__proto__指向构造函数原型,也就是将新对象链接到原型链上
3.将构造函数中的this指向新对象
4.构造函数中若有返回值,就直接返回;否则返回新对象
function Person(name, age){
this.name = name;
this.age = age;
}
Person.prototype.sayhi = function(){
console.log('hi', this.name)
}
function _new() {
let o = {};
let _self = Array.from(arguments).slice(0, 1)[0];
let _args = Array.from(arguments).slice(1);
o.__proto__ = _self.prototype;
_self.apply(o, _args);
return o;
}
var p = _new(Person, 'lucy', 12);
p.sayhi(); // hi, lucy