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>

 

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