Classes and Prototypes in JavaScript
Classes and prototypes are two ways to define objects in JavaScript. Classes were introduced in ES6, while prototypes have been a part of JavaScript since its inception.
Here's an example of how to define an object using a prototype:
javascript
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.sayHello = function() {
console.log("Hello, my name is " + this.name + " and I am " + this.age + " years old.");
}
var john = new Person("John", 30);
john.sayHello(); // prints "Hello, my name is John and I am 30 years old."
The Person function defines the object's properties, and the sayHello method is added to the object's prototype.
No comments:
Post a Comment