menu

JavaScript/Typescript - 16 Topics

DEEP DIVE INTO

JavaScript/Typescript

Topic:Adding and modifying properties and method

menu

In JavaScript, there are several ways to add and modify object properties and methods. The choice of method depends on your specific requirements and coding style. Here are common ways to add or modify properties and methods of an object:

Adding or Modifying Object Properties:

1. Dot Notation:

You can add or modify an object property using dot notation.

javascriptconst person = { name: "John" };
person.age = 30; // Adding a new property
person.name = "Jane"; // Modifying an existing property

2. Bracket Notation:

You can add or modify an object property using "bracket notation". This is useful when the property name is dynamic or contains special characters.

javascriptconst person = { name: "John" };
person["age"] = 30; // Adding a new property
person["first name"] = "Jane"; // Modifying an existing property with a special character in the name

3. Object.defineProperty():

You can use Object.defineProperty() to add or modify properties with additional attributes like configurability and writability.

javascriptconst person = {};
Object.defineProperty(person, "name", {
  value: "John",
  writable: true,
  configurable: true,
  enumerable: true,
});

Adding or Modifying Object Methods:

1. Function Declaration:

You can add a method to an object by declaring a function within the object literal.

javascriptconst person = {
  name: "John",
  greet: function() {
    console.log(`Hello, my name is ${this.name}.`);
  },
};

2. Method Shorthand (ES6):

In modern JavaScript (ES6 and later), you can use the method shorthand notation to define methods.

javascriptconst person = {
  name: "John",
  greet() { // Function keyword removed here
    console.log(`Hello, my name is ${this.name}.`);
  },
};

3. Object.assign():

You can use Object.assign() to copy properties and methods from one object to another.

javascriptconst person = { name: "John" };
const additionalInfo = {
  age: 30,
  greet() {
    console.log(`Hello, my name is ${this.name}.`);
  },
};
Object.assign(person, additionalInfo); // Adding properties and methods

4. Prototype Chain Modification:

For constructor functions, you can add or modify methods on the prototype chain, affecting all instances of the object.

javascriptfunction Person(name) {
  this.name = name;
}
Person.prototype.greet = function() {
  console.log(`Hello, my name is ${this.name}.`);
};

These methods allow you to add or modify properties and methods of objects in various ways, catering to your specific needs and coding style. Depending on your use case, choose the method that suits you best.

1280 x 720 px