What does the `#` symbol do in JavaScript? - javascript

I encountered code that contained the # sign. What is it used for? The code looks something like this:
class someObject{
#someMethod(){
//do something
}
}

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

Related

How can I take this inline function and convert it to a method while retaining access to this?

I have a JavaScript class that has this kind of structure:
class MyClass () {
myMethod() {
myCallback = (response) => {
// Do a bunch of stuff by referencing and altering properties in this
}
apiFunction(this.CLASS_PROP, myCallback);
}
}
myMethod is already pretty long, and the contents of myCallback make it even longer, so I tried converting it to this structure:
class MyClass () {
myMethod() {
apiFunction(this.CLASS_PROP, this.myCallback);
}
myCallback = (response) => {
// Do a bunch of stuff by referencing and altering properties in this
}
}
Whereas the first version works fine, the second one loses its reference to the MyClass instance and instead this is pointing to, I think, the call is the API that actually called it. I'm not positive as to why, but my theory is that "lexical context" doesn't mean where the function is defined, but where it's called.
But my question is, is there a way to break that function out of being inside of myMethod into an instance method of MyClass?
There are many ways to write that, one of them being
class MyClass {
myMethod() {
apiFunction(this.CLASS_PROP, r => this._myCallback(r));
}
_myCallback(response) {
// Do a bunch of stuff by referencing and altering properties in this
}
}
Note that in apiFunction there's an arrow function and _myCallback is an ordinary method (=not arrow). The other way around, like in your code, it won't work.
The underscore in _myCallback indicates a private method (a convention, not a special syntax).

Invoking private method from static method ES6

I am unable to call private or non static method from static method in class, below is the example
class a {
fun1(){
console.log('fun1');
}
static staticfun(){
console.log('staticfun');
this.fun1();
}
}
a.staticfun();
I am trying to expose only staticfun method which internally calls all private methods, but this gives me this.fun1 is not a function. I tried to find many ways to find it with 'this', but it does work.
How do I call private instance methods inside static methods?
fun1 is not a static function, so you need to define a new instance of the a class in order to call it:
class a {
fun1() {
console.log('fun1');
}
static staticfun() {
console.log('staticfun');
new this().fun1();
}
}
a.staticfun();
You should note that this is not good practice, though. You shouldn't have a static method relying on non-static logic.
A workaround would be to pass an instance of a to the static function, but that completely defies the point of having a static method in the first place.
Another way is to call the function directly from the class prototype (meaning literally the prototype property, not __proto__), if you want to avoid instantiating it.
class a {
fun1(){
console.log('fun1');
}
static staticfun(){
console.log('staticfun');
this.prototype.fun1();
}
}
a.staticfun();
First, read this SO question
It's possible, You can create an instance of class a and then invoke from the instance the method fun1.
Although, There is no sense to call a non-static method from a static one.
static means that this method belong to the object (not to the instance)
class a {
fun1(){
console.log('fun1');
}
static staticfun(){
console.log('staticfun');
const classInstance = new a()
classInstance.fun1();
}
}
a.staticfun();

How can I access the inherited static property from the inherited static method? [duplicate]

I have this class which does an internal call to a static method:
export class GeneralHelper extends BaseHelper{
static is(env){
return config.get('env:name') === env;
}
static isProd(){
return GeneralHelper.is('prod');
}
}
Are there any keywords I can use to replace the class name in the line below:
GeneralHelper.is('prod');
In PHP there are self, static etc. Does ES6 provide anything similar to these?
TY.
If you are calling the static function from inside an instance, the right way to refer to the static function of the class is:
this.constructor.functionName();
Call static methods from regular ES6 class methods
It's the same as calling a method on an ordinary object. If you call the GeneralHelper.isProd() method, the GeneralHelper will be available as this in the method, so you can use
class GeneralHelper {
static is(env) { … }
static isProd(){
return this.is('prod');
}
}
This will however not work when the method is passed around as a callback function, just as usual. Also, it might be different from accessing GeneralHelper explicitly when someone inherits isProd from your class and overwrites is, InheritedHelper.isProd() will produce other results.
If you're looking to call static methods from instance methods, see here. Also notice that a class which only defines static methods is an oddball, you may want to use a plain object instead.
Both of the answers here are correct and good, but I wanted to throw in an added detail based on this question title.
When I saw "ES6 - Call static method within a class" it sounded like "call a static method (from a non-static method) within a class". Def not what the initial question asker is asking in the details.
But for anyone who wants to know how to call a static method from a non-static method within a class you can do it like this:
class MyClass {
myNonStaticMethod () {
console.log("I'm not static.")
MyClass.myStaticMethod()
}
static myStaticMethod () {
console.log("hey, I'm static!")
}
}
MyClass.myStaticMethod() // will log "hey, I'm static!"
const me = new MyClass()
me.myNonStaticMethod() // will log "I'm not static" and then "hey, I'm static!"
The idea is that the static method is can be called without creating a new instance of the class. That means you can call it inside of a instance's method the same way you'd call it outside of the instance.
Again, I know that's not what the detail of the question was asking for, but this could be helpful other people.

ES6 - Call static method within a class

I have this class which does an internal call to a static method:
export class GeneralHelper extends BaseHelper{
static is(env){
return config.get('env:name') === env;
}
static isProd(){
return GeneralHelper.is('prod');
}
}
Are there any keywords I can use to replace the class name in the line below:
GeneralHelper.is('prod');
In PHP there are self, static etc. Does ES6 provide anything similar to these?
TY.
If you are calling the static function from inside an instance, the right way to refer to the static function of the class is:
this.constructor.functionName();
Call static methods from regular ES6 class methods
It's the same as calling a method on an ordinary object. If you call the GeneralHelper.isProd() method, the GeneralHelper will be available as this in the method, so you can use
class GeneralHelper {
static is(env) { … }
static isProd(){
return this.is('prod');
}
}
This will however not work when the method is passed around as a callback function, just as usual. Also, it might be different from accessing GeneralHelper explicitly when someone inherits isProd from your class and overwrites is, InheritedHelper.isProd() will produce other results.
If you're looking to call static methods from instance methods, see here. Also notice that a class which only defines static methods is an oddball, you may want to use a plain object instead.
Both of the answers here are correct and good, but I wanted to throw in an added detail based on this question title.
When I saw "ES6 - Call static method within a class" it sounded like "call a static method (from a non-static method) within a class". Def not what the initial question asker is asking in the details.
But for anyone who wants to know how to call a static method from a non-static method within a class you can do it like this:
class MyClass {
myNonStaticMethod () {
console.log("I'm not static.")
MyClass.myStaticMethod()
}
static myStaticMethod () {
console.log("hey, I'm static!")
}
}
MyClass.myStaticMethod() // will log "hey, I'm static!"
const me = new MyClass()
me.myNonStaticMethod() // will log "I'm not static" and then "hey, I'm static!"
The idea is that the static method is can be called without creating a new instance of the class. That means you can call it inside of a instance's method the same way you'd call it outside of the instance.
Again, I know that's not what the detail of the question was asking for, but this could be helpful other people.

Class variable in javascript class

The solution to this question suggested the use of John Resig's class implementation. This solution covers all my needs except:
How to declare a public global variable inside this class that can be accessed from outside?
I would like to establish something like the following:
var MyClass = Class.extend({
EVENT_NAME : 'event-name',
init : function() {
// ...
}
});
// Now another file can directly read this value without creating the class object
console.log( MyClass.EVENT_NAME );
The "only" way to do what you want to do is to use a function as the "class". This way you are declaring a "class" whose public "static" members can be accessed. Something like this:
function MyObject() {
// constructor stuff here
}
MyObject.EVENT_NAME = "event_name";
console.log(MyObject.EVENT_NAME); // No need to instantiate MyObject
However, seems to me like you are mixing concepts from statically typed languages with Javascript's more dynamic stuff. Why would you want to access a member of an object that has not been created?
Declare it in the window context or don't use the 'var' keyword:
window.globalVar = somevalue
globalVar = somevalue
var MyClass = Class.extend({
EVENT_NAME : 'event-name',
init : function() {
// ...
}
return {
event_name: function() { return EVENT_NAME; }
}
});
console.log( MyClass.event_name );
Actually, to be honest, I'm not sure how the above is going to work with .extend() as I've not actually used extend() before.
However, the return { name:value } technique is a pretty common way of exposing public instance methods in objects. It shouldn't take long to test it properly, sorry I didn't have a chance to do it myself.

Categories