因为无论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__'这两个点到同一个对象'人' –