Javascript 继承

直接上代码:

    var extend = function(destination, source, override) {
        if (override === undefined) override = true;
        for (var property in source) {
            if (!override && typeof(source[property]) == 'function' && destination.hasOwnProperty(property)) {
                destination[property] = (function(name, method) {
                    return function() {
                        this.base = source[name];
                        return method.apply(this, arguments);
                    }
                })(property, destination[property]);
            } else {
                destination[property] = source[property];
            }
        }

        return destination;
    };

    var bird = {
        fly : function() {
            return 'bird can fly';
        },
        eat : function(food) {
            return 'bird eat '+ food;
        }
    }

    var cat = {
        eat : function(food) {
            /*父类的同名方法*/
            //return this.base(food);
            return 'cat eat '+ food;
        }
    }

    extend(cat, bird, false);
    console.log(cat.eat('mouse'));

  

 

参考: http://www.cnblogs.com/sanshi/archive/2009/07/09/1519890.html

posted @ 2012-03-27 11:44  oneroundseven  阅读(218)  评论(0编辑  收藏  举报