函数化继承

迄今为止,所看到的继承模式的一个弱点就是我们没办法保护隐私。对象的所有属性都是可见的。我们没法得到私有变量和私有函数。

var mammal = function (spec) {
           var that = {},
           that.get_name = function () {
                        return spec.name;
           };
           that.says = function () {
                           return spec.saying  || ' ';
            };
            return that;
     };

name 和 saying 属性现在完全是私有的。他们只能通过get_name和says两个特权方法才可以访问。

在伪类模式中,构造器函数Cat不得不重复构造器Mammal已经完成的工作。在函数化模式中不在需要了

var cat = function (spec ) {
      spec.saying = spec.saying || 'meow';
      var that = mammal(spec);
      that.get_name = function () {
         return that .says() + ' ' + spec.name + ' ' +that.says();
         return that;
};

 

posted @ 2015-05-31 19:30  debug8man  阅读(119)  评论(0编辑  收藏  举报