调用new的过程发生:
1.新生成一个对象
2.链接到原型
3.绑定this
4.返回新对象(如果构造函数有自己 retrun 时,则返回该值)
手动new实现
function create() {
//创建一个新的对象
let obj = {}
//获取构造函数
let Con = [].shift.call(arguments)
//链接构造函数原型
obj.__proto__ = Con.prototype
//绑定this
let result = Con.apply(obj, arguments)
//判断是否返回object,确保new出来的是个对象
return typeof result === 'object' ? result : obj
}
/*关于arguments,由于arguments是类数组对象,并没有shift方法(此方法
位于Array原型对象上,Array.prototype.shift)因此此处需要使用call方法调用
在此处使用shift方法既可以获得constructor(The shift() method removes
the first element from an array and returns that removed element.
This method changes the length of the array.)还可以将其从arguments中
移除,使的后面调用时,无需再做进一步的处理 。
*/
网友评论