Clean β’ Professional
In JavaScript, object methods are functions stored as properties of an object. They allow objects to encapsulate behavior, enabling them to perform actions or computations related to their data. This section covers defining methods, usage of this .
this keyword to reference the objectβs data.
There are multiple ways to define methods in JavaScript:
a) Traditional Function Expression
Assign a function expression to a property using the function keyword.
const person = {
name: "John",
greet: function() {
console.log(`Hello, I'm ${this.name}`);
}
};
person.greet(); // "Hello, I'm John"
b) ES6 Shorthand Method Syntax
Define methods directly in object literals without the function keyword.
const person = {
name: "John",
greet() {
console.log(`Hello, I'm ${this.name}`);
}
};
person.greet(); // "Hello, I'm John"
Caution:
this.this from the surrounding lexical scope.this.this or as callbacks inside methods.const person = {
name: "John",
greet: () => {
console.log(`Hello, I'm ${this.name}`);
}
};
person.greet(); // "Hello, I'm undefined"
Methods can be added after object creation:
const person = { name: "John" };
person.greet = function() {
console.log(`Hello, I'm ${this.name}`);
};
person.greet(); // "Hello, I'm John"
Computed Property Names (ES6+):
const methodName = "sayHi";
const person = {
name: "John",
[methodName]() {
console.log(`Hi, I'm ${this.name}`);
}
};
person.sayHi(); // "Hi, I'm John"
this Keyword in MethodsIn a method, this refers to the object the method is called on.
const person = {
name: "Alice",
greet() {
console.log(`Hello, I'm ${this.name}`);
}
};
person.greet(); // "Hello, I'm Alice"
Context Loss:
Extracting a method may lose its this context:
const greet = person.greet;
greet(); // "Hello, I'm undefined" or TypeError in strict mode
Solutions:
Bind the method:
const boundGreet = person.greet.bind(person);
boundGreet(); // "Hello, I'm Alice"
Use .call() or .apply():
greet.call(person); // "Hello, I'm Alice"
Wrap in a function for callbacks:
setTimeout(function() {
person.greet();
}, 1000); // "Hello, I'm Alice" after 1 second
a) Constructor Functions
Per-instance methods:
function Person(name) {
this.name = name;
this.greet = function() {
console.log(`Hello, I'm ${this.name}`);
};
}
const john = new Person("John");
john.greet(); // "Hello, I'm John"
Prototype methods (shared across instances): Prototype methods are more memory-efficient for multiple instances.
Person.prototype.greet = function() {
console.log(`Hello, I'm ${this.name}`);
};
const alice = new Person("Alice");
alice.greet(); // "Hello, I'm Alice"
b) ES6 Classes
Methods defined inside the class are automatically added to the prototype:
class Person {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello, I'm ${this.name}`);
}
}
const bob = new Person("Bob");
bob.greet(); // "Hello, I'm Bob"
Β