javascript new操作符做了什么事情?实现new操作
1、创建了一个空对象obj。
2、将实例的原型obj.__proto__指向构造函数的原型对象Func.prototype。
3、绑定this值(让Func中的this指向obj,并执行Func的函数体)。
4、判断Func的返回值类型:如果无返回值 或者 返回一个非对象值,则将 obj 作为新对象返回;否则会将 result 作为新对象返回。
function Func(name,age){ this.name=name; this.age=age; }; function mock(constructor,...params){ let obj = {}; obj.__proto__=constructor.prototype; let result = constructor.apply(obj,params) result == 'obj' ? obj=result : obj return obj }; console.log(mock(Func,'xhj',20))

浙公网安备 33010602011771号