因爲無論tony
和peter
分享該陣列,這是在person
。只有一個數組,你只是改變它的狀態。
您創建tony
和peter
後,在內存中有這樣的(忽略細節):
+−−−−−−−−−−+
person−−−−−−−−−−−−−−−−−−−+−+−−>| (Object) |
// +−−−−−−−−−−+ +−−−−−−−−−−−+
| | | stomach |−−−−−>| (Array) |
| | +−−−−−−−−−−+ +−−−−−−−−−−−+
| | | length: 0 |
| | +−−−−−−−−−−−+
+−−−−−−−−−−−+ | |
tony−−−−>| (Object) | | |
+−−−−−−−−−−−+ | |
| __proto__ |−−+ |
+−−−−−−−−−−−+ |
|
+−−−−−−−−−−−+ |
peter−−−>| (Object) | |
+−−−−−−−−−−−+ |
| __proto__ |−−−−+
+−−−−−−−−−−−+
無論您通過tony.__proto__.stomach
或peter.__proto__.stomach
訪問陣列(通過原型鏈),你所訪問只是一個陣列。當您通過eat
上推"shawarma"
,一個陣列的狀態,體改,可見無論你走的路才能到它:
+−−−−−−−−−−+
person−−−−−−−−−−−−−−−−−−−+−+−−>| (Object) |
// +−−−−−−−−−−+ +−−−−−−−−−−−−−−−+
| | | stomach |−−−−−>| (Array) |
| | +−−−−−−−−−−+ +−−−−−−−−−−−−−−−+
| | | length: 1 |
| | | 0: "shawarma" |
+−−−−−−−−−−−+ | | +−−−−−−−−−−−−−−−+
tony−−−−>| (Object) | | |
+−−−−−−−−−−−+ | |
| __proto__ |−−+ |
+−−−−−−−−−−−+ |
|
+−−−−−−−−−−−+ |
peter−−−>| (Object) | |
+−−−−−−−−−−−+ |
| __proto__ |−−−−+
+−−−−−−−−−−−+
你會被給予tony
和peter
他們自己解決這個stomach
S,大概除去stomach
從person
(儘管你可以離開它,如果你想直接使用person
以及使用它作爲原型):
let person = {
stomach: [], // You may or may not want to remove this, depending
eat(food) {
this.stomach.push(food);
}
};
let tony = {
__proto__: person,
stomach: []
};
let peter = {
__proto__: person,
stomach: []
};
tony.eat("shawarma");
console.log(tony.stomach); // shawarma
console.log(peter.stomach); // empty
因爲JavaScript正在尋找'peter .__ proto __。stomach'。請參閱https://basarat.gitbooks.io/typescript/docs/classes-emit.html –
https://stackoverflow.com/questions/16394709/why-this-behaviour-proto-vs-prototype –
'__proto__'這兩個點到同一個對象'人' –