/** 测试案例 */
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'));
js 模拟new
最新推荐文章于 2024-09-14 18:52:56 发布