高级前端
js
【Q338】js 中在 new 的时候发生了什么

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

Issue 欢迎在 Gtihub Issue 中回答此问题: Issue 341 (opens in a new tab)

Author 回答者: XJHxjh0118 (opens in a new tab)

  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 : {};
}

Author 回答者: shfshanyue (opens in a new tab)

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

Author 回答者: Vi-jay (opens in a new tab)

  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

Author 回答者: yuerdev (opens in a new tab)

  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没用啊

Author 回答者: bigbigDreamer (opens in a new tab)

  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;
}

Author 回答者: Ghaining (opens in a new tab)

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