What are .extend and .prototype used for?

Extend:

The JavaScript / jQuery extend method copies all properties from the source to the destination object. The primary use of the extend method is in class declarations with the purpose of creating a class (sub-class) that is the child of another parent class (super-class). It can be used to subclass both the built-in objects as well as the user-defined (custom) classes.

Syntax:

class child_class extends parent_class { 
    // class definition goes here
}

Example:

Javascript



filter_none

edit
close

play_arrow

link
brightness_4
code

// Parent Class
class Animal {
  
  constructor(name) {
    this.name = name;
  }
}
  
// Child Class
class Dog extends Animal {
  
  constructor(name) {
    // the super keyword to used to call 
    // the constructor of the parent class
    super(name); 
    this.name = name;
  }
}

chevron_right


Prototype:

The prototype property is a unique feature of the JavaScript language. The prototype property acts as a member of objects. Its primary use is to allow the addition of new properties (members or functions) to object constructors. It is also used to inherit features from one to another. The need for prototyping arises because JavaScript does not allow addition of new property to an existing object constructor.

Syntax:

ClassName.prototype.property = value;

// For class members:
ClassName.prototype.member_name = member_value; 

// For class methods:
ClassName.prototype.function_name = function() {
    // function definition
};

Example:

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

class Employee {
  
    let firstName;
     let lastName;
  
    // constructor
    Employee (first, last) {
        this.firstName = first;
        this.lastName = last;
    }
}
  
// add class data member
Employee.prototype.email = "example@gmail.com";
  
// add class member function
Employee.prototype.fullName = function() {
      return this.firstName + " " + this.lastName;
};

chevron_right


full-stack-img




My Personal Notes arrow_drop_up

Data Structure & Algorithms Lead (C++) Developer Student Club (Google) || MERN Stack Web Developer || Machine Learning Enthusiast || Skilled in C, C++, Java, Python, HTML, CSS, JS, React, NodeJS, Mongoose, Git among others

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.