lixiaojuan12 / Summary-of-code

手写代码爽起来~~~
0 stars 0 forks source link

2. 内置new的实现 #2

Open lixiaojuan12 opened 4 years ago

lixiaojuan12 commented 4 years ago
function Fn(x,y){
    this.x=x;
    this.y=y;
}
function _new(func){
    let params=Array.from(arguments).slice(1);
    let obj=Object.create(func.prototype);
    let result=func.apply(obj,params);
    //如果类中有return并且是引入数据类型,那么返回类中的return
    if(result!==null&&(typeof result==='object'||typeof result==='function')){
         return result;
    }
    return obj;
}
let f1=_new(Fn,10,20);