JavaScript 手写 new.md


function myNew(fn, ...args) {
  // 内存中创建一个对象
  let obj = {};
  // 这个新对象内部的[[prototype]]指针被赋值为构造函数的prototype属性
  if (fn.prototype) {
    obj.__proto__ = fn.prototype;
  }
  // 执行构造函数内部代码(给新对象添加属性)
  let res = fn.call(obj, ...args);
  // 如果构造函数返回非空对象,则返回该对象;否则返回刚创建的对象
  if (res && ["object", "function"].includes(typeof res)) {
    return res;
  }
  return obj;
}

function Person(name, age) {
  this.name = name;
  this.age = age;
}

function Person1(name, age) {
  this.name = name;
  this.age = age;
  return {
    name,
    age,
  };
}

let person = myNew(Person, "Simbel", 18);
let person1 = myNew(Person1, "New", 20);
console.log(person);
console.log(person1);

 上一篇
N 皇后 N 皇后
N 皇后const solveNQueens = function (n) { // 已摆放皇后的列下标 const cols = new Set(); // 已摆放皇后的左斜线 右上→左下 // 计算某个坐标是否在这个左
下一篇 
JavaScript 手写 apply 方法.md JavaScript 手写 apply 方法.md
// ES5 实现 Function.prototype.myApply1 = function (ctx, args) { // 不指定this或者传入null或者undifined时,this指向window ctx = ctx
  目录