首页 > 技术文章 > javascript 继承

huang_yong_jian 2014-01-13 00:04 原文

        function Shape(id) {
            this.id = id;
        }
        Shape.prototype.name = "shape";
        Shape.prototype.toString = function () {
            var result = [];
            if (this.constructor.parent) {
                result[result.length] = this.constructor.parent.toString();
            }
            result[result.length] = this.name;
            return result.join(', ');
        };

        function TwoDShape(id) {
            TwoDShape.parent.constructor.call(this, id);
        }
        //TwoDShape.prototype = new Shape();
        //TwoDShape.prototype = Shape.prototype;
        var F = function () {
        }
        F.prototype = Shape.prototype;
        TwoDShape.prototype = new F();
        TwoDShape.prototype.constructor = TwoDShape;
        TwoDShape.parent = Shape.prototype;
        TwoDShape.prototype.name = "2D shape";

        function Triangle(id, side, height) {
            Triangle.parent.constructor.call(this, id);
            this.side = side;
            this.height = height;
        }

        //Triangle.prototype = new TwoDShape();
        //Triangle.prototype = TwoDShape.prototype;
        var F = function () {
        }
        F.prototype = TwoDShape.prototype;
        Triangle.prototype = new F();
        Triangle.prototype.constructor = Triangle;
        Triangle.parent = TwoDShape.prototype;
        Triangle.prototype.name = "triangle";
        Triangle.prototype.getArea = function () {
            return this.side * this.height / 2;
        }

        // YUI
        function extend(Child, Parent) {
            var F = function () {
            };
            F.prototype = Parent.prototype;
            Child.prototype = new F();
            Child.prototype.constructor = Child;
            Child.parent = Parent.prototype;
        }

        function Person(name){
            this.name = name;
        }
        Person.prototype.say = function(){
            return "Hi, I' m " + this.name + ". ";
        }
        
        extend(Developer,Person);
        function Developer(name, language){
            this.language = language;
            Developer.parent.constructor.call(this,name);
        }
        Developer.prototype.say = function(){
            return Developer.parent.say.call(this) + "I love " + this.language + ".";
        }

        /*
        var javaDeveloper = new Developer("A","Java");
        var javascriptDeveloper = new Developer("B","Javascript");
        alert(javaDeveloper.say());
        alert(javascriptDeveloper.say());
        */

推荐阅读