JavaScript 中的 `#` 符号有什么作用?

What does the `#` symbol do in JavaScript?

我遇到了包含 # 符号的代码。这有什么用途?代码看起来像这样:

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

它是一个 sigil(而不是运算符),表示该成员是私有的——在这种情况下,private method, but it's also used for private fields

您不能在声明 class 之外的代码中使用私有方法或私有字段。例如:

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

这是一个实验性提案。您可以使用 #

定义私有 JavaScript 方法

更多信息,您可以参考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.


你可以使用 ES5 实现类似的东西(只是为了简单解释),你可以在其中模拟类似私有方法的东西(JavaScript 本身没有。)

例如:

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
  }
}

上面只会暴露someObj中的init方法,可以调用为someObj.init(),而你的someMethod在外面是无法访问的它的父方法。

示例:

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

哈希用于定义私有class字段