JavaScript private methods

前端 未结 30 2121
-上瘾入骨i
-上瘾入骨i 2020-11-22 08:16

To make a JavaScript class with a public method I\'d do something like:

function Restaurant() {}

Restaurant.prototype.buy_food = function(){
   // something         


        
30条回答
  •  面向向阳花
    2020-11-22 09:03

    ES2021 / ES12 - Private Methods

    Private method names start with a hash # prefix and can be accessed only inside the class where it is defined.

    class Restaurant {
    
      // private method
      #private_stuff() {
        console.log("private stuff");
      }
    
      // public method
      buy_food() {
        this.#private_stuff();
      }
    
    };
    
    const restaurant = new Restaurant();
    restaurant.buy_food(); // "private stuff";
    restaurant.private_stuff(); // Uncaught TypeError: restaurant.private_stuff is not a function
    

    This is an experimental proposal. ECMAScript 2021 version is expected to be released in June 2021.

提交回复
热议问题