How to Use Parameters and Built-in Functions in Object-Oriented JavaScript?

Estimated read time 1 min read

To use parameters and built-in functions in object-oriented JavaScript, you can follow these steps:

  1. Define classes with constructor functions that take parameters as input and set them as properties of the object.
  2. Use built-in JavaScript functions such as Object.defineProperties to define getters and setters for object properties.
  3. Use methods to implement the object’s behavior and make use of the object’s properties and other built-in functions.

Example code:

class User {
  constructor(name, age) {
    this._name = name;
    this._age = age;
  }

  get name() {
    return this._name;
  }
  
  set name(value) {
    this._name = value;
  }

  get age() {
    return this._age;
  }

  set age(value) {
    if (value < 0) {
      throw new Error('Age must be positive');
    }
    this._age = value;
  }

  toString() {
    return `Name: ${this.name}, Age: ${this.age}`;
  }
}

const user = new User('John', 30);
console.log(user.toString()); // Name: John, Age: 30

Note: This is just an example, you can modify it as per your requirements.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply