zoukankan      html  css  js  c++  java
  • javascript 的继承实例

    shape.prototype = {
        getEdge:function(){
            return this.edge;
        },
        getArea:function(){
            return this.a*this.b;
        }
    }
    function shape(edge, a, b)
    {
        this.edge = edge;
        this.a = a;
        this.b = b;
    }
    
    //三角形继续形状
    triangle.prototype = new shape();
    triangle.prototype.getName = function(){alert('I am a triangle');}
    function triangle(bottom ,height)
    {
        shape.call(this, 3, bottom ,height);
    }
    
    
    //四边形继续形状
    rectangle.prototype = new shape();
    rectangle.prototype.getName = function(){alert('I am a rectangle');}
    rectangle.prototype.getArea = function(){alert('I rewrite parent getArea method');}
    function rectangle(bottom ,height)
    {
        shape.call(this, 4, bottom ,height);
    }
    
    var t = new triangle(10, 5);
    
    var r = new rectangle(10, 5);
    
    
    console.dir(r);

    继承方面,javascript中的每个对象都有一个内部私有的链接指向另一个对象 (或者为 null),这个对象就是原对象的原型. 这个原型也有自己的原型, 直到对象的原型为null为止. 这种一级一级的链结构就称为原型链.

    基于原型链的继承

    javascript对象有两种不同的属性,一种是对象自身的属性,另外一种是继承于原型链上的属性.下面的代码演示了当访问一个对象的属性时,到底发生了什么

    // 假定我们有个对象o,并且o所在的原型链如下:
    // {a:1, b:2} ---> {b:3, c:4} ---> null
    // 'a'和'b'是o自身的属性.
    
    // 该例中,用"对象.[[Prototype]]"来表示这个对象的原型.
    // 这只是一个纯粹的符号表示(ECMAScript标准中也这样使用),不能在实际代码中使用.
    
    console.log(o.a); // 1
    // a是o的自身属性吗?是的,该属性的值为1
    
    console.log(o.b); // 2
    // b是o的自身属性吗?是的,该属性的值为2
    // o.[[Prototype]]上还有一个'b'属性,但是它不会被访问到.这种情况称为"属性遮蔽".
    
    console.log(o.c); // 4
    // c是o的自身属性吗?不是,那看看o.[[Prototype]]上有没有.
    // c是o.[[Prototype]]的自身属性吗?是的,该属性的值为4
    console.log(o.d); // undefined
    // d是o的自身属性吗?不是,那看看o.[[Prototype]]上有没有.
    // d是o.[[Prototype]]的自身属性吗?不是,那看看o.[[Prototype]].[[Prototype]]上有没有.
    // o.[[Prototype]].[[Prototype]]为null,原型链已到顶端,没有d属性,返回undefined
    在原型链上查找属性比较耗时,对性能有副作用,这在性能要求苛刻的情况下很重要。另外,试图访问不存在的属性时会遍历整个原型链。

    更详细的继承介绍:http://www.cnblogs.com/sanshi/archive/2009/07/08/1519036.html

    MDN继承介绍:https://developer.mozilla.org/zh-CN/docs/JavaScript/Guide/Inheritance_and_the_prototype_chain

  • 相关阅读:
    Java GUI图形界面开发工具
    python操作MySQL数据库
    国外五大股票交易系统及其源码
    五个抄底摸高的交易系统和源代码
    海龟交易系统源码
    模式识别话题
    几种常见模式识别算法整理和总结
    比较好的开源人脸识别软件
    利用开源程序(ImageMagick+tesseract-ocr)实现图像验证码识别
    JSONObject与JSONArray的使用
  • 原文地址:https://www.cnblogs.com/siqi/p/3300231.html
Copyright © 2011-2022 走看看