new 做了什麼事?


Posted by YongChenSu on 2020-12-09

先備知識 call()

function test() {
  console.log(this)
}

test.call('123') // {string: '123'}
test.call({}) // {}

new 關鍵字做的事

  1. 產生新的 obj
  2. call constructor,把 obj 當作 this 丟進去,便完成初始化的物件
  3. 設定 proto 到指定的 prototype
  4. 回傳 obj
  5. 完成 instance
function Dog(name) {
  this.name = name
}

Dog.prototype.getName = function() {
  return this.name
}

Dog.prototype.sayHello = function() {
  console.log(this.name)
}

var d = new Dog('hi')
var b = newDog('hello')

function newDog(name) {
  var obj = {}
  Dog.call(obj, name)
  console.log(obj) // {name: 'hello'}
  obj.__proto__ = Dog.prototype
  return obj
}

b.sayHello() // hello
console.log(b.getName()) // hello


參考資源


#程式導師實驗計畫第四期 #前端 #new







Related Posts

[TensorFlow Certification Day14] TensorFlow Embedded文本相關model

[TensorFlow Certification Day14] TensorFlow Embedded文本相關model

Java Stream intermediate operations are lazily executed

Java Stream intermediate operations are lazily executed

Golang-Advance- GO routine

Golang-Advance- GO routine


Comments