前端面试题之手写new

76 阅读1分钟

首先,我们看new都有哪些功能

1、new 可以创建一个新对象obj 2、new拥有构造函数,将新对象obj的原型__proto__与构造函数的原型prototype连接 3、执行构造函数,并将构造函数的this绑定到新对象obj上

如下

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

Person.prototype.sayHello = function () {
  console.log(`hello,my name is ${this.name}, I am ${this.age} years old`)
}

const tom = new Person('tom', 18)
console.log(tom.name, tom.age) // tom 18
tom.sayHello() // hello,my name is tom, I am 18 years old

那我们来实现以上功能

function myNew () {
  // 1、new 可以创建一个新对象obj
  const obj = new Object()
  // 2、获取构造函数
  const Constructor = [].shift.call(arguments)
  // 3、将新对象obj的原型与构造函数原型连接
  Constructor.prototype = obj.__proto__
  // 4、将构造函数的this指向新对象
  const result = Constructor.apply(obj, arguments)
  // 5、如果result是对象则返回,否则返回新对象obj
  return result instanceof Object ? result : obj
}

const Jerry = myNew(Person, 'Jerry', 20)
console.log(Jerry.name, Jerry.age) // Jerry, 20
Jerry.sayHello() // hello,my name is Jerry, I am 20 years old