If you have any query feel free to chat us!
Happy Coding! Happy Learning!
Adding behavior to objects can be done in different ways in JavaScript. One common way is to use the prototype property of a function constructor to add methods to the objects created by that constructor.
Here's an example:
javascriptCopy code
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.`);
}
const person1 = new Person('John', 30);
person1.sayHello(); // logs "Hello, my name is John and I am 30 years old."
In this example, we define a Person
constructor function that takes two parameters (name
and age
) and sets them as properties on the newly created object using the this
keyword. We then add a method sayHello()
to the prototype of the Person
constructor function.
When we create a new Person
object (person1
), it inherits the sayHello()
method from the prototype. We can then call this method on the person1
object to execute it. The this
keyword in the sayHello()
method refers to the object on which the method is called (person1
in this case).
This is a common pattern in JavaScript for adding behavior to objects. By adding methods to the prototype of a constructor function, we can share that behavior across all instances of objects created by that constructor. This can be more memory-efficient than adding methods directly to the objects themselves, as the methods are only stored once in memory, in the constructor's prototype object, rather than being duplicated for each object.
When will I get my course?
Now, Your query was resolved.
Quick answers to common questions about our courses, quizzes, and learning platform
I am not able to access videos from second class and further. I have already completed first class