脫離OO,擁抱「行爲委託」式編程

脫離OO,擁抱「行爲委託」式編程

今天分享的雞湯來自於「有書共讀」——《你的衣服淘汰的太快,竟然是網絡時代的錯》css

任何新方法,任何能夠使事情更易完成的方法都是科技,這纔是對科技的正確理解。編程

相信你們都很熟悉Javascript「面向對象」編程,可是這種設計模式對於JS來講,我認爲不是一個簡單的科學的設計模式。先來上代碼設計模式

  • 面向對象編程網絡


function Widget(width, height) {
        this.width = width || 50;
        this.height = height || 50;
        this.$elem = null;
    }

    Widget.prototype.render = function ($where) {
        if(this.$elem){
            this.$elem.css({
                width : this.width + "px",
                height : this.height + "px"
            }).appendTo( $where )
        }
    };

    //子類
    function Button(width, height, label) {
        //調用super 構造函數
        Widget.call(this, width, height);
        this.label = label || "Default";

        this.$elem = $("<button>").text( this.label );
    }
    //繼承
    Button.prototype = Object.create( Widget.prototype );
    //重寫render
    Button.prototype.render = function ($where) {
        //構造函數
        Widget.prototype.render.call(this, $where);

        this.$elem.click( this.onClick.bind( this ));
    };

    Button.prototype.onClick = function () {
        console.log("Button"+this.label+"Clicked!");
    };

    $( document ).ready( function () {
        var $body = $(document.body);
        var btn1 = new Button(125, 30, "hello");
        var btn2 = new Button(150, 40, "world!");

        btn1.render($body);
        btn2.render($body);
    })

總結:在上面代碼中出現了顯示的僞多態,即經過Widget.call和Widget.prototype.render.call從「子類」方法中引用「父類方法」中的基礎方法。原本就不適合爲何要強行使用呢?真的好看麼?app

  • 行爲委託方式函數


var Widget = {
        init : function (width, height) {
            this.width = width || 50;
            this.height = height || 50;
            this.$elem = null
        },
        insert : function ($where) {
            if(this.$elem){
                this.$elem.css({
                    width : this.width + "px",
                    height : this.height + "px"
                }).appendTo($where)
            }
        }
    };

    var Button = Object.create(Widget);

    Button.setup = function (width, height, label) {
        //委託調用
        this.init(width, height);
        this.label = label;

        this.$elem = $("<button>").text( this.label );
    };

    Button.build = function ($where) {
        //委託調用
        this.insert($where);
        this.$elem.click( this.onClick.bind( this ));
    };

    Button.onClick = function () {
        console.log("Button" + this.label + "clicked!");
    };

    $( document ).ready( function () {
        var $body = $( document.body );
        var btn1 = Object.create( Button );
        btn1.setup(125, 30, "Hello");

        var btn2 = Object.create( Button );
        btn2.setup(150, 40, "World! ");

        btn1.build($body);
        btn2.build($body);
    })

總結:兩種編程的風格不一樣若是說簡潔度可能OO會比較好一點,可是對相關聯能夠更好的支持關注分離原則,建立和初始化並不須要合併爲一個步驟。ui

相關文章
相關標籤/搜索