JavaScript Object Methods

JavaScript Object Methods

What are Object Methods? Methods are actions that can be performed on objects. Methods are functions stored as property values. In a method, ‘this’ refers to the owner object. 什么是对象方法? 方法是可以在对象上执行的操作。方法是作为属性值存储的函数。在方法中,“this”指的是所属的对象。

Syntax: objectName.methodName() 语法: objectName.methodName()

Object creation Example:

let student = {
  name: "Karthika",
  class: "12th",
  section: "A",
  studentDetails: function () {
    return this.name + " " + this.class + " " + this.section + " ";
  }
};

// Display object data
console.log(student.studentDetails());

对象创建示例:

let student = {
  name: "Karthika",
  class: "12th",
  section: "A",
  studentDetails: function () {
    return this.name + " " + this.class + " " + this.section + " ";
  }
};

// 显示对象数据
console.log(student.studentDetails());

Output: Karthika 12th A 输出: Karthika 12th A

If we give methodname without () brackets, it returns the function definition: console.log(student.studentDetails); 输出: 如果我们提供方法名而不带 () 括号,它将返回函数定义: console.log(student.studentDetails);

Output: [Function: studentDetails] 输出: [Function: studentDetails]

Explanation: “this” Keyword In the example above, this refers to the student object. this.name means the name property of the student object. this.class means the class property of the student object. this.section means the section property of the student object. 解释:“this”关键字 在上面的示例中,this 指的是 student 对象。this.name 表示 student 对象的 name 属性。this.class 表示 student 对象的 class 属性。this.section 表示 student 对象的 section 属性。

Using Object.values() Object.values() creates an array from the property values:

const person = { name: "Karthi", age: 30, city: "New York" };
// Create an Array from the Properties
const myArray = Object.values(person);
let text = myArray.toString();
console.log(text);

使用 Object.values() Object.values() 可以从属性值创建一个数组:

const person = { name: "Karthi", age: 30, city: "New York" };
// 从属性创建数组
const myArray = Object.values(person);
let text = myArray.toString();
console.log(text);

Output: Karthi,30,New York 输出: Karthi,30,New York