constructor function javascript es6 code example
Example 1: javascript class constructor
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
const person = new Person("John Doe", 23);
console.log(person.name);
Example 2: javascript classes
class MyClass {
constructor(FirstProperty, SecondProperty, etcetera) {
this.firstProperty = FirstProperty;
this.secondProperty = SecondProperty;
}
method(Parameters) {
}
get getBothValues()
{
return [firstProperty, secondProperty];
}
}
Example 3: javascript class
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
get area() {
return this.calcArea();
}
calcArea() {
return this.height * this.width;
}
}
const square = new Rectangle(10, 10);
console.log(square.area);
Example 4: how to create instance of class in javascript
class Hello {
person(name){
this.name = name;
}
constructor(name){
this.person(name);
console.log(`Hello ${this.name}`);
}
}
const helloInstance = new Hello('john doe');
Example 5: class declaration in javascript
class NameOfClass {
obj="text";
obj2="some other text";
}
console.log(new NameOfClass);