Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Js Object Methods in JavaScript

Js Object Methods in JavaScript

? JavaScript Object Methods

In JavaScript, object methods are functions stored as object properties. They allow objects to perform actions using their own data.


? What Is a Method?

A method is just a function inside an object.

let person = {  firstName: "Alice",  lastName: "Johnson",  fullName: function () {    return this.firstName + " " + this.lastName;  }};console.log(person.fullName()); // "Alice Johnson"

? this refers to the object the method belongs to (person in this case).


?? Defining Object Methods

? Regular Function

let car = {  brand: "Toyota",  model: "Corolla",  start: function () {    return this.brand + " " + this.model + " started!";  }};

? ES6 Shorthand

let car = {  brand: "Toyota",  model: "Corolla",  start() {    return `${this.brand} ${this.model} started!`;  }};

? Reusable Methods Using Constructor

function Person(name) {  this.name = name;  this.sayHello = function () {    return "Hi, I'm " + this.name;  };}let p1 = new Person("Bob");console.log(p1.sayHello()); // Hi, I'm Bob

? Common Built-in Object Methods

MethodDescription
Object.keys(obj)Returns array of keys
Object.values(obj)Returns array of values
Object.entries(obj)Returns array of [key, value] pairs
Object.assign(target, source)Copies values from source to target
Object.hasOwnProperty(key)Checks if key exists on object

? Example

let user = {  name: "Eve",  age: 30};console.log(Object.keys(user));    // ["name", "age"]console.log(Object.values(user));  // ["Eve", 30]console.log(Object.entries(user)); // [["name", "Eve"], ["age", 30]]

? Arrow Functions as Methods (?? Avoid)

Avoid arrow functions when using this in object methods:

let obj = {  name: "Test",  greet: () => {    console.log(this.name); // ? 'this' is not bound to obj  }};

Use regular functions or shorthand method syntax instead.


? Summary

  • Object methods = functions inside objects

  • Use this to access object properties

  • Prefer regular functions or method shorthand (not arrow functions)

  • Use built-in methods like Object.keys(), Object.assign(), etc.


Would you like to learn how to dynamically add or remove methods from objects?

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql