A way to encapsulte ( add privacy ) to models in the MVC?

前端 未结 2 1111
盖世英雄少女心
盖世英雄少女心 2021-01-20 02:54

I namespace my models and a single controller like this:

var MC = {};

and then added properties as needed.

For example, the code th

相关标签:
2条回答
  • 2021-01-20 03:11

    Is there a simple way to add privacy to my models and still have them accessible as properties in an object?

    Obviously, you then will need to make the whole object private. And yes, that will work as any other privacy in JavaScript, too - a closure.

    Have a look at the module pattern (there are many tutorials out on the web about this).

    0 讨论(0)
  • 2021-01-20 03:30

    you can do this with closures.

    var MyNamespace = {};
    MyNamespace.MyClass = (function() {
        function privateMethod() {
            // ...
        }
    
        function publicMethod() {
            // can call privateMethod() from in here
        }
    
        return ({
            publicMethod: publicMethod
        });
    }());
    

    This will create an object called MyNamespace.MyClass with one private method and one public method. In your case you probably want to do this for each model class. Have their init methods be public and hide their other methods.

    0 讨论(0)
提交回复
热议问题