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

【JS 專案 - 02】 為你的 TodoList 加點函數小菜

【JS 專案 - 02】 為你的 TodoList 加點函數小菜

React-[核心篇]- React渲染功能在後台是怎麼運作的?

React-[核心篇]- React渲染功能在後台是怎麼運作的?

軍事訓練役如何改變了我

軍事訓練役如何改變了我


Comments