What does the `#` symbol do in JavaScript?

女生的网名这么多〃 提交于 2020-12-13 03:14:34

问题


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

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

回答1:


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



回答2:


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



回答3:


hash is used to define private class fields



来源:https://stackoverflow.com/questions/64968964/what-does-the-symbol-do-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!