Adding Behaviour to Objects

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Lecture 199:- Adding Behaviour to Objects

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.

22. Constructors And Prototypes

2 Comments

@niteshguptav63
niteshguptav63 Nov 17, 2024 at 1:39 PM

I am not able to access videos from second class and further. I have already completed first class

@niteshguptav63
niteshguptav63 Nov 16, 2024 at 10:56 AM

When will I get my course?

@admin79
admin79 Nov 17, 2024 at 1:29 PM

Now, Your query was resolved.

Frequently Asked Questions About Sciaku Courses & Services

Quick answers to common questions about our courses, quizzes, and learning platform

Didn't find what you're looking for?

help_center Contact Support