What are .extend and .prototype used for ?
Last Updated :
20 Feb, 2023
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
class Animal {
constructor(name) {
this .name = name;
}
}
class Dog extends Animal {
constructor(name) {
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;
Employee (first, last) {
this .firstName = first;
this .lastName = last;
}
}
Employee.prototype.email = "example@gmail.com" ;
Employee.prototype.fullName = function () {
return this .firstName + " " + this .lastName;
};
|
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...