I have a class like the following:
const Module = {
Example: class {
constructor(a) {
this.a = a;
}
static fromString(s) {
// parsing code
return new Module.Example(a);
}
}
}
This works so far, but accessing the current class constructor via the global name Module.Example
is kind of ugly and prone to breaking.
In PHP, I would use new self()
or new static()
here to reference the class that the static method is defined in. Is there something like this in Javascript that doesn't depend on the global scope?
Summary: The new keyword is used in javascript to create a object from a constructor function. The new keyword has to be placed before the constructor function call and will do the following things: Creates a new object. Sets the prototype of this object to the constructor function's prototype property.
The keyword self is used to refer to the current class itself within the scope of that class only whereas, $this is used to refer to the member variables and function for a particular instance of a class.
The new operator lets developers create an instance of a user-defined object type or of one of the built-in object types that has a constructor function.
You might sometimes use self to capture the context of this before it is destroyed by some function. Unfortunately self is also an alias for window , the global top-level object.
You can just use this
inside the static method. It will refer to the class itself instead of an instance, so you can just instantiate it from there.
If you need to access the constructor from an instance function, you can use this.constructor
to get the constructor without specifying its name.
Here's how:
const Module = {
Example: class Example {
constructor(a) {
this.a = a;
}
static fromString(s) {
// parsing code
return new this(s);
}
copy() {
return new this.constructor(this.a);
}
}
}
const mod = Module.Example.fromString('my str');
console.log(mod) // => { "a": "my str"
console.log(mod.copy()) // => { "a": "my str" }
console.log('eq 1', mod === mod) // => true
console.log('eq 2', mod === mod.copy()) // => false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With