美文网首页
[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类与继承

    一、ECMAScript 5标准中的类 1、定义原型类 2、原型类继承 下面是一典型的关于原型继承的代码。 3、静...

  • [JavaScript]“类”与“继承”

    The rule is simple: if a property or a method is not foun...

  • JavaScript类与继承

  • javascript的类与继承

    javascript的类与继承 javascript的类与一般的面向对象语言有很大的不同,类的标识是它的构造函数,...

  • 继承

    继承:让子类拥有父类的属性和方法//继承是类与类之间的关系谈继承是一个悖论:JavaScript是函数编程流派,是...

  • JavaScript 面向对象的那些事儿

    一、类与实例 1、类的声明 2、生成实例 生成实例,都是用new方法,如下: 二、类与继承 JavaScript的...

  • JavaScript - 继承和类

    JavaScript - 继承和类 在这一篇中,我要聊聊 JavaScript 中的继承和“类”。 首先跟你请教下...

  • javascript 类继承

    1.面向过程与面向对象 1.1面向过程 面向过程就是分析出解决问题所需要的步骤,然后用函数把这些步骤一步一步实现,...

  • JavaScript 类继承与原型继承的区别

    点击上方 "程序员小乐"关注, 星标或置顶一起成长 每天凌晨00点00分, 第一时间与你相约 每日英文 Somet...

  • JavaScript 类继承与原型继承的区别

    在 ES6 之前,JavaScript 实现两个对象的继承一般有两种方法。 一种方法是利用 this 与构造函数。...

网友评论

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

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