最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

What does the `#` symbol (number sign) do inside a JavaScript class? - Stack Overflow

programmeradmin4浏览0评论

I encountered code that contained the # sign. What is it used for? The code looks something like this:

class someObject{
  #someMethod(){
    //do something 
  }
}

I encountered code that contained the # sign. What is it used for? The code looks something like this:

class someObject{
  #someMethod(){
    //do something 
  }
}
Share Improve this question edited May 14, 2023 at 13:38 dumbass 27.2k4 gold badges36 silver badges73 bronze badges asked Nov 23, 2020 at 13:03 Ran MarcianoRan Marciano 1,5315 gold badges16 silver badges33 bronze badges 0
Add a comment  | 

3 Answers 3

Reset to default 18

It's a sigil (rather than an operator) that indicates that the member is private — in this case, a private method, but it's also used for private fields.

You can't use a private method or private field in code outside the class declaring them. For instance:

class Example {
    doSomething() {
        this.#method("from doSomething"); // <== Works
    }
    #method(str) {
        console.log("method called: " + str);
    }
}
const e = new Example();
e.doSomething();
e.#method(); // <=== FAILS

This is an experimental proposal. You can define Private JavaScript methods Using #

For more info, you can refer to the MDN docs

Class properties are public by default and can be examined or modified outside the class. There is however an experimental proposal to allow defining private class fields using a hash # prefix.


You can achieve something similar using ES5 (just for the sake of simplicity to explain), where you can simulate something like Private methods (which JavaScript doesn't have one natively.)

For example:

function someObj() { //assuming this is a class definition
  function someMethod() { //private method which is not accessible outside someObj

  }

  function init() { //initializes some methods or code, private methods can be used here
    someMethod();
  }

  return {
    init //only exposes the init method outside
  }
}

In the above, it will only expose the init method from the someObj which can be called as someObj.init(), whereas your someMethod will not be accessible outside of its parent method.

Example:

someObj.init(); //works
someObj.someMethod(); //won't be accessible

hash is used to define private class fields

发布评论

评论列表(0)

  1. 暂无评论