Home » Design » jQuery » Javascript equivalent to PHP __construct

Javascript equivalent to PHP __construct

posted in: Design, Javascript, jQuery, PHP, Programming 0

The constructor method is a special method for creating and initializing an object created within a class. In other words, it’s a function that runs automatically whenever the object is instantiated.

Using the constructor method

class Person {

  constructor(name) {
    this.name = name;
  }

  introduce() {
    console.log(`Hello, my name is ${this.name}`);
  }

}

const otto = new Person('Otto');

otto.introduce();

If you don’t provide your own constructor, then a default constructor will be supplied for you. If your class is a base class, the default constructor is empty:

constructor() {}

If your class is a derived class, the default constructor calls the parent constructor, passing along any arguments that were provided:


constructor(...args) {
  super(...args);
}

Just as a reminder: the super keyword is used to access and call functions on an object’s parent (more information here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/super)

Look at these other resources on Javascript constructor:

https://stackoverflow.com/questions/61213185/javascript-equivalent-to-php-construct

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/constructor


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.