Open zxdfe opened 1 year ago
- 创建一个空对象
- this指向这个空对象
- 执行构造函数代码,给this添加属性和方法
- 把this作为返回值返回
function Qwer(name){ this.name = name; this.age = 18; this.fn = function(){ console.log(this.name); } } const qwe = new Qwer('pink'); qwe.fn();
手写new不是指的这个哈
function myNew(fn, ...args) {
let obj = new Object()
obj.__proto__ = fn.prototype
let res = fn.call(obj, ...args)
if (res && (typeof res === 'object' || typeof res === 'function')) return res
else return obj
}
手写一个new是直接用原型继承吗??
1、创建一个空对象 2、构造函数中的this指向这个对象 3、执行构造函数,给空对象赋值 4、返回这个对象