美文网首页
[JavaScript]“类”与“继承”

[JavaScript]“类”与“继承”

作者: __Liu__ | 来源:发表于2016-12-21 15:09 被阅读0次
    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

    相关文章

      网友评论

          本文标题:[JavaScript]“类”与“继承”

          本文链接:https://www.haomeiwen.com/subject/xgyqvttx.html