js手动实现new方法

new

  1. 新生成了一个对象
  2. 新对象隐式原型链接到函数原型
  3. 调用函数绑定this
  4. 返回新对象

核心代码:

function _new(fun) {
  return function() {
    let obj = {
      __proto__: fun.prototype
    }
    fun.apply(obj, arguments)
    return obj
  }
}

测试用例:

function person(name, age) {
  this.name = name
  this.age = age
}
let obj = _new(person)('LL', 100)
console.log(obj) //{name: 'LL', age: 100}

猜你喜欢

转载自blog.csdn.net/ll18781132750/article/details/81111634