Daily-Question icon indicating copy to clipboard operation
Daily-Question copied to clipboard

【Q338】js 中在 new 的时候发生了什么

Open shfshanyue opened this issue 4 years ago • 6 comments

shfshanyue avatar Jun 10 '20 12:06 shfshanyue

  1. 创建了一个新对象
  2. 链接到原型
  3. 绑定this指向 4.返回这个对象
function _new() {
 let obj = {}
 let Con = [].shift.call(arguments)
 obj.__proto__ = Con.prototype
 let result = Con.apply(obj, arguments)
 return typeof obj === 'object' ? obj : {}
}

XJHxjh0118 avatar Nov 25 '20 03:11 XJHxjh0118

  1. 创建一个新的对象
  2. this 指向实例,并且执行函数
  3. 如果没有显式返回,则默认返回这个实例

shfshanyue avatar Jun 03 '21 03:06 shfshanyue

  1. 创建了一个新对象
  2. 链接到原型
  3. 绑定this指向 4.返回这个对象
function _new() {
 let obj = {}
 let Con = [].shift.call(arguments)
 obj.__proto__ = Con.prototype
 let result = Con.apply(obj, arguments)
 return typeof obj === 'object' ? obj : {}
}

如果构造器返回null 就不对了 因为 typeof null === 'object' 所以应该用 obj instanceof Object

Vi-jay avatar May 12 '22 02:05 Vi-jay

  1. 创建了一个新对象
  2. 链接到原型
  3. 绑定这个指向 4.返回这个对象
function _new() {
 let obj = {}
 let Con = [].shift.call(arguments)
 obj.__proto__ = Con.prototype
 let result = Con.apply(obj, arguments)
 return typeof obj === 'object' ? obj : {}
}

这个result没用啊

yuerdev avatar Jun 23 '22 08:06 yuerdev

  1. 关联原型
  2. 调用函数,绑定参数
  3. 返回执行,特别需要处理 nullobject 场景
function myNew(...rest) {
    const fn = [].slice.call(rest, 0, 1)[0];
    const params = [].slice.call(rest, 1);
    const ret = Object.create(fn.prototype);
    const result = fn.apply(ret, params);
    return typeof result === 'object' ? result || ret : ret ;
}

bigbigDreamer avatar Aug 25 '22 15:08 bigbigDreamer

function myNew(fn, ...args) {
  const instance = Object.create(fn.prototype);
  const ret = fn.apply(instance, args);
  return typeof ret === "object" && ret !== null ? ret : instance;
}

Ghaining avatar Aug 08 '23 17:08 Ghaining