手写new操作符(完整版包含格式检验)
作者:互联网
function Dog(name) {
this.name = name;
}
Dog.prototype.bark = function () {
console.log('wangwang');
};
Dog.prototype.sayName = function () {
console.log('my name is ' + this.name);
};
/* let sanmao = new Dog('三毛');
sanmao.sayName();
sanmao.bark(); */
// Ctor:构造函数 params:给构造函数传递的实参(数组)
// + Object.create([prototype]) 创建一个空对象,并且让其__proto__指向[prototype]
// + Object.create(null) 创建一个不具备原型链的空对象
/* function _new(Ctor, ...params) {
// 格式校验:函数 & 有原型对象 & 不是Symbol/BigInt
if (typeof Ctor !== "function") throw new TypeError(`${Ctor} is not a constructor!`);
let name = Ctor.name,
proto = Ctor.prototype;
if (/^(Symbol|BigInt)$/i.test(name) || !proto) throw new TypeError(`${name} is not a constructor!`);
// 1.创建当前类的一个实例对象
/!* let obj = {};
obj.__proto__ = Ctor.prototype; *!/
let obj = Object.create(Ctor.prototype);
// 2.把构造函数像普通函数一样执行,但是this需要指向创建的实例对象
let result = Ctor.call(obj, ...params);
// 3.看函数的返回值,如果没有写返回值,或者返回的是原始值,我们默认返回实例对象;如果返回的是对象,则以自己返回的为主;
if (result !== null && /^(object|function)$/i.test(typeof result)) return result;
return obj;
} */
const _new = function _new(Ctor, ...params) {
if (typeof Ctor !== "function") throw new TypeError(`${Ctor} is not a constructor!`);
let name = Ctor.name,
proto = Ctor.prototype,
obj,
result;
if (/^(Symbol|BigInt)$/i.test(name) || !proto) throw new TypeError(`${name} is not a constructor!`);
obj = Object.create(proto);
result = Ctor.call(obj, ...params);
if (result !== null && /^(object|function)$/i.test(typeof result)) return result;
return obj;
};
let sanmao = _new(Dog, '三毛');
sanmao.bark(); //=>"wangwang"
sanmao.sayName(); //=>"my name is 三毛"
console.log(sanmao instanceof Dog); //=>true
标签:function,obj,name,result,new,手写,完整版,Ctor 来源: https://blog.csdn.net/Donnien/article/details/118093354