Home  >  Article  >  Web Front-end  >  In js, what can be used to access the properties and methods of an object

In js, what can be used to access the properties and methods of an object

下次还敢
下次还敢Original
2024-05-07 20:12:19564browse

The methods to access object properties and methods in JavaScript are: dot notation (.) to directly access properties and methods, such as: person.name, person.greet(). Square brackets ([]) support the use of dynamic strings or variables as attribute names, such as: person['first name']. The object spread operator (...) copies properties and methods into another object, such as: const newPerson = { ...person }.

In js, what can be used to access the properties and methods of an object

Accessing JavaScript object properties and methods

In JavaScript, there are many ways to access the properties and methods of an object. method.

1. Dot notation (.)

The most direct way is to use dot notation (.), as shown below:

<code>const person = {
  name: 'John',
  age: 30,
  greet: function() {
    console.log('Hello, my name is ' + this.name);
  }
};

// 访问属性
console.log(person.name); // 输出: John

// 访问方法
person.greet(); // 输出: Hello, my name is John</code>

2. Square brackets ([])

Square brackets ([]) are also a way to access properties, which allow you to use dynamic strings or variables as property names, as shown below:

<code>const person = {
  'first name': 'John',
  age: 30,
  greet: function() {
    console.log('Hello, my name is ' + this.name);
  }
};

// 使用动态字符串访问属性
console.log(person['first name']); // 输出: John

// 使用变量访问属性
const propName = 'age';
console.log(person[propName]); // 输出: 30</code>

3. Object spread operator (...)

Object spread operator (...) can copy the properties and methods of an object to another object , as shown below:

<code>const person = {
  name: 'John',
  age: 30,
  greet: function() {
    console.log('Hello, my name is ' + this.name);
  }
};

const newPerson = {
  ...person
};

// newPerson 现在具有 person 的所有属性和方法
console.log(newPerson.name); // 输出: John
newPerson.greet(); // 输出: Hello, my name is John</code>

The above is the detailed content of In js, what can be used to access the properties and methods of an object. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:How to use alert in jsNext article:How to use alert in js