diveDylan / blog

My blog, detail is in the issues list
2 stars 0 forks source link

手写new关键字 #66

Open diveDylan opened 4 years ago

diveDylan commented 4 years ago

new operator 创建一个空的简单JavaScript对象(即{}); 链接该对象(即设置该对象的构造函数)到另一个对象 ; 将步骤1新创建的对象作为this的上下文 ; 如果该函数没有返回对象,则返回this

diveDylan commented 4 years ago
function newFn(fn, ...rest) {
     const obj = {}
     obj.__proto__  = fn.prototype
     const result = fn.apply(obj, rest)
     return result ? result : obj
 }