[removed] Calling private method from prototype method

后端 未结 3 1300
你的背包
你的背包 2021-01-30 18:08

I am sure that this must be a pretty common question but after scouring the internets for several hours, I have not found an answer. Here is the question:

Suppose that

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-30 19:04

    Define your Dog "class" in a closure. Then you can have shared priveliged functions. Just know you will have to be careful about this binding properly when you call it.

    var Dog = (function() {
      function Dog() {};
    
      // Common shared private function, available only to Dog.
      var privateHelper = function() { ... };
    
      Dog.prototype = new Mammal();
    
      Dog.prototype.eat = function() {
        privateHelper()
        // Or this if the helper needs to access the instance.
        // privateHelper.call(this);
        ...
      };
    
      return Dog;
    })();
    

    A function on a prototype is still just a function. So follows the same scope and closure access rules as any another function. So if you define your entire Dog constructor and prototype and a secluded island of scope that is the self executing function, you are welcome to share as much as you like without exposing or polluting the public scope.

    This is exactly how CoffeeScript classes compile down to JS.

提交回复
热议问题