[JavaScript]“类”与“继承”

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

prototype chain
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,980评论 0 23
  • 沈茵茵大学毕业后进入上海知名外企德普斯投资公司财务部当了一名助理职员,入职不久的她在一次公司聚会上与财务总监莫之航...
    酷听听书阅读 443评论 0 1
  • 春节前,童瑶案算是大白于天下,最终以“童瑶”自首告终。 也正是这件事,让我又一次认识到网络的双刃剑。 童瑶事件是啥...
    大地行者阅读 759评论 1 1
  • 你收集的海报和身体DNA一样多 喝掉的咖啡和烟灰缸里的烟蒂一样 写下的一字一句日夜兼程 追赶翻红的股指,长期服用雌...
    文姬阅读 177评论 0 1
  • 考研兄你好! 兄弟听说你要考研,恭喜你做了你人生中第一个重大决定,不过作为经历过你人生中第一个转折点的我想要给你说...
    Jachinzhao阅读 344评论 2 6