찾다

 >  Q&A  >  본문

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;

            }

        }

    }

    //下面省掉的代码可以保证通过传入arg来确定执行module1还是module2

}

var module1 = SomeFunction("module1");

module1.setValue("xxxx");

console.log(module1.getValue());//期望打印xxxx

module1.moduleFunc();//期望也打印xxxx</code>

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

PHPzPHPz2913일 전248

모든 응답(1)나는 대답할 것이다

  • PHP中文网

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

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    <code>    self.module1 = function() {

            var insideBase = self.base();

     

            var ret = {

                moduleFunc: function() {

                    console.log(insideBase.getValue());

                }

            };

             

            return jQuery.extend(ret, insideBase);

        }</code>

    module2也是一样。

    회신하다
    0
  • 취소회신하다