var a = {
x:10,
calculate:function(z){
return this.x+this.y+z;
}
}
var b = {
y:20,
__proto__:a // b extends a
}
var c = {
y:30,
__proto__:a
}
//call the inherited method
b.calculate(3); // 10+20+3 = 33
c.calculate(3); // 10+30+3 = 43
The rule is simple: if a property or a method is not found in the object itself (i.e. the object has no such an *own *property), then there is an attempt to find this property/method in the prototype chain. If the property is not found in the prototype, then a prototype of the prototype is considered, and so on, i.e. the whole prototype chain (absolutely the same is made in class-based inheritance, when resolving an inherited *method *— there we go through the class chain). The first found property/method with the same name is used. Thus, a found property is called *inherited *property. If the property is not found after the whole prototype chain lookup, then undefined value is returned.
JavaScripte有種很明顯的“鏈式邏輯”,當前對象/作用域找不到引用的屬性或者方法,則沿著鏈向上尋找,此處是在 b對象 中沒有找到calculate方法,則沿著“原型鏈(prototype/class chain)”向上尋找,在 a對象 里找到了calculate方法...,在調用過程中,會沿著鏈依次尋找到最近的名稱相同屬性或者方法并使用(The first found property/method with the same name is used)。如果沒有找到,則返回 undefined