Closures vs. classes for encapsulation?

前端 未结 3 986
我在风中等你
我在风中等你 2021-02-02 10:10

I\'m new to JS (from C++/etc), and it\'s just occurred to me that closures seem to be a simpler and more convenient way to handle encapsulation than classes. This code seems to

3条回答
  •  囚心锁ツ
    2021-02-02 10:20

    This is an old question, but there are a few things the answers are missing so I figure I'd add to this.

    First, as commenters love to point out, there aren't any real classes in javascripts, we just mimic them with closures. Here's what the javascript tutorials call a "class:"

    function Class1(){
        var privateState='blah';
        this.get=function(){
            return privateState;
        }
    }
    var myObj=new Class1();
    

    Importantly, the get method is just a closure. So, this is basically the same as your code. Because closures must reference the environment in which they were created (this is how they can use the private internal state data), they are more costly than just using a public function. So if you have a static method that doesn't require the internal state, you should add it to Class1 instead by using the prototype key word:

    Class1.prototype.staticMethod=function(){...};
    

    This way, the static method can be used through the prototype chain without using up extra memory with unnecessary closures. You could also achieve this with your method by adding static methods outside of your AddPropertyfunction.

    So, in the end the only difference between a formal javascript "class" and your AddProperty function is that when you actually use the class constructor, the class appears in the object's prototype chain, whereas your objects just inherit directly from the generic object prototype. You could certainly write code that uses this distinction, but that would probably be bad code.

提交回复
热议问题