• javascript 继承


        //对象冒充实现继承
        function Person() {
            this.speak = function () {
                alert("我是人类");
            };
        }
    
        function Chinese() {
            Person.call(this);
        }
        var p = new Chinese();
        p.speak();
    
    //对象冒充与原型继承
        function Person(sColor) {
            this.color = sColor;
        }
    
        Person.prototype.sayColor = function () {
            alert(this.color);
        };
    
        function Chinese(sColor, sName) {
    
            Person.call(this, sColor);//对象冒充继承属性
    
            this.name = sName;
        }
    
        Chinese.prototype = new Person();//原型继承方法
    
        Chinese.prototype.sayName = function () {
            alert(this.name);
        };
    
        var p = new Chinese("red", "高聪");
        p.sayColor();
        p.sayName();
    //Shape - superclass
    function Shape() {
      this.x = 0;
      this.y = 0;
    }
    
    Shape.prototype.move = function(x, y) {
        this.x += x;
        this.y += y;
        console.info("Shape moved.");
    };
    
    // Rectangle - subclass
    function Rectangle() {
      Shape.call(this); //call super constructor.
    }
    
    Rectangle.prototype = Object.create(Shape.prototype);
    
    var rect = new Rectangle();
    
    rect instanceof Rectangle //true.
    rect instanceof Shape //true.
    
    rect.move(1, 1); //Outputs, "Shape moved."
    该方法属于ES5规范,如果浏览器环境不支持也可以自行实现,如下:
    
    Object.create = Object.create || function (obj) {
                var F = function () {};
                F.prototype = obj;
                return new F();
            }

     

  • 相关阅读:
    [日常训练]大灾难
    [cf235D]Graph Game
    [日常训练]选课
    [日常训练]挂科
    [学习笔记]概率&期望
    [日常训练]yayamao的神题
    [学习笔记]原根
    LOJ#2132. 「NOI2015」荷马史诗
    LOJ#2131. 「NOI2015」寿司晚宴
    LOJ#2129. 「NOI2015」程序自动分析
  • 原文地址:https://www.cnblogs.com/gaocong/p/6951064.html
Copyright © 2020-2023  润新知