javascript - 初学js闭包遇到的问题,如何在闭包时实现继承
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | <code> 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;
}
}
}
}
var module1 = SomeFunction( "module1" );
module1.setValue( "xxxx" );
console.log(module1.getValue());
module1.moduleFunc();
|
现在希望module1和module2执行后返回的object中有base中getValue和setValue两个方法,
同时保证moduleFunc可以访问到base中的val
而且允许module1和module2中使用自己的setValue和getValue覆盖base里默认提供的方法
如何做到继承或者覆盖呢?
可以使用jQuery.extend如果需要的话