Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"new self()" equivalent in Javascript

Tags:

javascript

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?

like image 751
Christoph Burschka Avatar asked Jun 19 '17 10:06

Christoph Burschka


People also ask

What is new student () in JavaScript?

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.

Is self the same as this in JavaScript?

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.

What is the new operator in JavaScript?

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.

Can you use self in JavaScript?

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.


1 Answers

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
like image 168
casraf Avatar answered Oct 25 '22 09:10

casraf