Sunday, November 17, 2024
Google search engine
HomeLanguagesJavascriptWhat are .extend and .prototype used for ?

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




// 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;
  }
}


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




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;
};


Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments