昨天講完了範例,今天一樣從底層運作機制來看吧。
prototype chain
function Person(name) {
  this.name = name
}
Person.prototype.getName = function() {
  return this.name
}
Person.prototype.sayHello = function() {
  console.log(this.name)
}
var a = new Person("aaa")
a.sayHello()
var b = new Person("bbb")
b.sayHello()
console.log(a.__proto__ === Person.prototype) //true
先來說一下當執行:a.sayHello()後會做什麼?
a.__proto__有沒有sayHello,沒有的話就往上層找。
(
a.__proto__= Person.prototype)
這是new幫我們設定好的
上面的範例到這一層就找到了。但先假設還找不到的話,會找到哪邊?
a.__proto__.__proto__,沒有的話就往上層找。
(
a.__proto__.__proto__ = object.prototype)
a.__proto__.__proto__.__proto__即找到頂端null
(
a.__proto__.__proto__.__proto__= null)
由.__proto__所構成的稱為prototype chain(原型鏈),和scope chain很像都是往上找的概念。
new 做了什麼
function Person(name) {
  this.name = name
}
Person.prototype.getName = function() {
  return this.name
}
Person.prototype.sayHello = function() {
  console.log(this.name)
}
var a = newPeople("aaa")
a.sayHello()
function newPeople(name) {
  var obj = {}  //產生一個新的object
  Person.call(obj, name) //call constructor,把新的object當作this丟進去。這樣就做完初始化。
  obj.__proto__ = Person.prototype //再把obj.__porto__ 連到 Person.prototype
  return obj
}
function newPeople(name)即是new做的事。