js 模拟new

在这里插入图片描述

/** 测试案例 */
function student(name) {
    this.cons = name;
} 
student.prototype.test = '678'; //创建测试方法

let a = new student('12412412');
console.log('a: ', a); //new 出的结果

/** new方法实现 */
function CopyNew(testFun, ...arr) { //模拟 new
    /**
	* Object.create(testFun.prototye), 将testFun.prototype对象赋给obj的原型
	* new Object(testFun.prototype), 将testFun.prototype赋给obj本身
	*/
    let obj = Object.create(testFun.prototype); 
    /**
    * 以obj作为testFun的this,执行testFun
	* 那么testFun里的执行的变量,就会赋给obj
	*/
    let obj2 = testFun.call(obj, ...arr); 
	  if (
	    (typeof obj2 === 'object' || typeof obj2 === 'function') &&
	    obj2 !== null
	  ) {
	  	//当函数return的是null,function,object,array等时, 不返回新生成的对象,返回函数返回值
	    return obj2;
	  }
    return obj;
}
CopyNew(student);
console.log('CopyNew(student);: ', CopyNew(student, '1252523'));
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值