问题
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