search

Home  >  Q&A  >  body text

javascript - 初学js闭包遇到的问题,如何在闭包时实现继承

function SomeFunction(arg){
    var self = this;
    self.module1 = function(){            
        return {                 
            moduleFunc: function(){
                console.log(val);
            }
        };
    }
    
    self.module2 = function(){            
        return {                 
            moduleFunc: function(){
                console.log(val);
            }
        };
    }
    
    self.base = function(){
        var val;
        return {
            getValue: function(){
                return val;
            },
            setValue: function(arg){
                val = arg;
            }
        }
    }
    //下面省掉的代码可以保证通过传入arg来确定执行module1还是module2
}
var module1 = SomeFunction("module1");
module1.setValue("xxxx");
console.log(module1.getValue());//期望打印xxxx
module1.moduleFunc();//期望也打印xxxx

现在希望module1和module2执行后返回的object中有base中getValue和setValue两个方法,
同时保证moduleFunc可以访问到base中的val
而且允许module1和module2中使用自己的setValue和getValue覆盖base里默认提供的方法
如何做到继承或者覆盖呢?
可以使用jQuery.extend如果需要的话

PHPzPHPz2902 days ago247

reply all(1)I'll reply

  • PHP中文网

    PHP中文网2017-04-10 16:58:30

        self.module1 = function() {
            var insideBase = self.base();
    
            var ret = {
                moduleFunc: function() {
                    console.log(insideBase.getValue());
                }
            };
            
            return jQuery.extend(ret, insideBase);
        }

    module2也是一样。

    reply
    0
  • Cancelreply