var New =function(fn){
//1.新建空对象
var obj={};
//2.实例对象的__proto__等于构造函数的prototype
obj.__proto__=fn.prototype;
//3. 将 arguments 对象转为数组
var args = [].slice.call(arguments);
//4.去除构造函数
args.shift();
//5. 通过调用call、apply方法执行构造函数并改变this对象
var result = fn.apply(obj, args);
//6. 判断返回值,如果是Object类型就直接返回,否则返回实例对象本身
if(Object.prototype.toString.call(result)=="[object Object]" ){
return result
}else{
return obj;
}
}
var Fun=function(sex){
this.name='hty';
this.sex=sex;
}
const fun=New(Fun,'123');
console.log(fun.name);//hty
console.log(fun.sex);//123
javascript new 一个函数发生的过程
最新推荐文章于 2023-12-26 20:19:22 发布