![]() |
VOOZH | about |
Classes: These are almost similar to functions, except they use a class keyword instead of a function keyword. Another important difference between functions and classes is that functions can be called in code before they are defined whereas classes must be defined before a class object is constructed in JavaScript, else running the code will throw a Reference error.
Defining a class: A class can be defined by using a class keyword along with a constructor function to initialize it.
Syntax:
class Classname {
constructor(property1, property2) {
this.property1 = property1;
this.property2 = property2;
}
}
Example: The following example describes for a simple classes.
Output:
Employee {name: 'Suraj', id: 533}
id: 533
name: "Suraj"
[[Prototype]]: Object
Class Expressions: We can also define a class using class expressions. They can be of two types namely "named" or "unnamed". The name of a class can be accessed by the name property.
Syntax:
let Employee = class {
constructor(name, id) {
this.name = name;
this.id = id;
}
}
Example:
Output:
Employee1 Intern
Class methods: We can also define methods inside classes. It can be with or without parameters.
Syntax:
class Classname {
constructor(property1, property2) {
this.property1 = property1;
this.property2 = property2;
}
method1() { ... }
}
Example:
Output:
Name of Employee: Suraj Works in Finance department
Proxies: Proxies are objects that are used to redefine the fundamental operations of an object. It allows us to create a proxy of another object.
Parameters:
A proxy object accepts two parameters described below:
Syntax:
const target = {
property1: "first property",
property2: "second property"
};
const handler = { ... };
const proxy1 = new Proxy(target, handler);
Example:
Output:
GeeksforGeeks Computer science portal
Since the handler is empty, it does not affect the target. Thus, the proxy behaves as its original target.
We can also define operations within the handler to change the properties of the proxy from its original target. For this, we need to use the get() handler which can access the properties of the target and manipulate the properties inside the proxy. The reflect class helps to apply the original properties of the target to the proxy.
Example: We applied if condition in the handler, to check for "property2" of the target, the output should be changed from the original property of the target.
Output:
GeeksforGeeks For computer science geeks