js 面向對象代碼

貼上一段同事寫的代碼,值的紀念

<script type="text/javascript">

    //創建箱子類
    function Box(option) {
        var self = this;
        var _option = {
            height: 12,
            width: 12
        };
        //合併參數對象 : 記得引用Jquery.js
        $.extend(_option, option);

        this.height = _option.height;
        this.width = _option.height;
        //綁定事件列表
        var _events = {};

        //創建一個方法,並帶有回調函數
        this.push = function(option, callback) {
            if (option.height > this.height) {
                console.error("over height", this);
                return;
            }
            if (option.width > this.width) {
                console.error("over width", this);
                return;
            }

            //判斷是否有回調函數
            if (callback instanceof Function)
            //調用回調函數,並給它傳值(參數:_option)
                callback.call(this, _option);
        }

        //綁定事件
        this.on = function(name, event) {
            if (name == null || !name)
                return null;

            if (!(event instanceof Function))
                if (self[name] instanceof Function) {
                    return self[name]();
                }

            if (event instanceof Function)
                _events[name] = self[name] = function() {
                    event.apply(this);
                    return this;
                }
        }

        //解除綁定事件
        this.unbind = function(name) {
            delete self[name];
            delete _events[name];

            //鏈式表達式
            return this;
        }
    }

    //創建box1對象
    var box1 = new Box();

    //創建box2對象
    var box2 = new Box();

    //調用方法
    box1.push({
        height: 12,
        width: 12
        //回調函數
    }, function(option) {

        console.log("push回調函數已調用..", option);
    });

    //動態給對象綁定事件
    box1.on("click", function() {
        this.width += 10;
        console.log("width遞增10,click事件被調用..", this.width);
    });
    box1.on("heihei", function() {
        console.log("heihei事件被調用..", this.width);
    });

    //事件普通調用
    box1.click();
    //鏈式表達式調用方法
    box1.on("click").click().heihei().on("heihei");

    //打印box1的寬度
    console.log(box1.width);
    //打印box2的寬度
    console.log(box2.width);

    //解除綁定事件
    box1.unbind("heihei");
    //測試解除
    box1.heihei();

</script>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章