Search This Blog

2023/04/20

Function vs Class in javascript

 In JavaScript, both classes and functions can be used to create objects and define object-oriented behavior.

However, there are some key differences between the two.

Syntax:
A class is defined using the class keyword, while a function can be defined
using the function
keyword or the arrow function (=>) syntax.

Constructors:
Classes have a constructor method that is called when an object is created
using the new keyword.
This method is used to initialize object properties and can be defined using
the constructor keyword.

Functions can also be used as constructors, but they require the use of the
new keyword and
a special property called prototype to define methods and properties for the
objects they create.

Inheritance:
Classes support inheritance through the use of the extends keyword, allowing
them to inherit
properties and methods from a parent class.

Functions can also be used for inheritance through the use of the prototype
property,
but this approach can be more complex and less intuitive than using classes.

Methods:
Classes can define methods directly within the class definition.

Functions can define methods by adding them to the prototype property.

Here's an example that demonstrates the difference between a class and a
function in JavaScript:


Class Example:
// Defining a class
class Person {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello, my name is ${this.name}`);
}
}
const person = new Person('John');
person.greet(); // Output: "Hello, my name is John"
Function Example

// Defining a function
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
console.log(`Hello, my name is ${this.name}`);
};
const person = new Person('John');
person.greet(); // Output: "Hello, my name is John"

No comments:

Post a Comment