function Dog(name) {
this.name = name;
}
Dog.prototype.bark = function () {
console.log('wangwang');
}
Dog.prototype.sayName = function () {
console.log('my name is ' + this.name);
}
/*
* 重写内置NEW
* Ctor:constructor 想创造谁的实例,就传递哪一个构造函数 Dog
* params:NEW构造函数时候给其传递的实参值 ['三毛']
*/
/* function _new(Ctor, ...params) {
let obj,
result;
// @1 创造CTOR的实例对象
obj = {};
obj.__proto__ = Ctor.prototype;
// @2 把构造函数当做普通函数执行,让方法中的THIS指向创造的实例对象
result = Ctor.call(obj, ...params);
// @3 观察方法执行的返回结果:如果没有写返回值,或者返回的是原始值类型的值,都已返回实例对象为主;如果返回的是一个对象/函数,则以自己返回的为主...
if (result !== null && /^(object|function)$/i.test(typeof result)) return result;
return obj;
} */
function _new(Ctor, ...params) {
// 格式校验:能被NEW的,首先是个函数,其次需要有prototype属性,而且还不能是Symbol/BigInt构造函数...
if (typeof Ctor !== 'function' || !Ctor.prototype || Ctor === Symbol || Ctor === BigInt) throw new TypeError(`${Ctor} is not a constructor`);
let obj,
result;
obj = Object.create(Ctor.prototype);
result = Ctor.call(obj, ...params);
if (Ctor === Number || Ctor === String || Ctor === Boolean) result = Object(result);
if (result !== null && /^(object|function)$/i.test(typeof result)) return result;
return obj;
}
let sanmao = _new(Dog, '三毛');
sanmao.bark();
sanmao.sayName();
console.log(sanmao instanceof Dog); //=>true
重写内置new方法完整版(包含Object.create()以及格式校验)
最新推荐文章于 2023-12-29 00:56:59 发布