如何实现一个 new
new 的作用
- 创建一个JavaScript空对象(即{});
- 为步骤1新创建的对象添加属性__proto__,将该属性链接至构造函数的原型对象 ;
- 将步骤1新创建的对象作为this的上下文 ;
- 如果该函数没有返回对象,则返回this。
function _new(fn, ...arg) {
const obj = Object.create(fn.prototype);
const ret = fn.apply(obj, arg);
return ret instanceof Object ? ret : obj;
}
function mynew () {
const obj = Object.create({});
let Fn = [].shift.call(arguments);
let returnObj = Fn.apply(obj, arguments);
obj.__proto__ = Fn.prototype
return Object.prototype.toString.call(returnObj) == '[object Object]' ? returnObj : obj;
}
验证
function _new(fn, ...arg) {
const obj = Object.create(fn.prototype);
const ret = fn.apply(obj, arg);
return ret instanceof Object ? ret : obj;
}
function People() {
this.name = 'paopao'
this.age = 3
}
const p = _new(People)
console.log(JSON.stringify(p))
console.log(p.__proto__ === People.prototype)
console.log(p.name)
console.log(p.constructor === People)
扩展
[].slice.call( arguments )
Array.prototype.slice.call( arguments )