js中new操作符

2020-07-03  本文已影响0人  AAAlex_65a0

js中的new操作符MDN中是这样说的。new 运算符创建一个用户定义的对象类型的实例或具有构造函数的内置对象的实例。
我们使用new就是实例化一个类的过程。这个过程中会进行以下几步:

function myNew(constructor, ...rest) {
    // let obj = {}
    // obj.__proto__ = constructor.prototype
    // constructor.call(obj, ...rest)
    // return obj

    let child= Object.create(constructor.prototype)
    constructor.apply(child,rest)
    return child
}

现在我们试一下

// 自己的new
function myNew(constructor, ...rest) {
  if (typeof constructor === "function") {
    // let obj = {}
    // obj.__proto__ = constructor.prototype
    // constructor.call(obj, ...rest)
    // return obj
    let child= Object.create(constructor.prototype)
    constructor.apply(child,rest)
    return child


  }
}

// 构造函数F
function F(name) {
  this.name = name
  this.hello=function () {
      console.log('hello')
  }
}
F.prototype.ok=function(){
  console.log('ok')
}
//  当前构造函数的实例
let f = myNew(F,'alex')


console.log(f.name) // alex
f.hello() // hello
f.ok() // ok
上一篇 下一篇

猜你喜欢

热点阅读