As a developer, you want to have the ability to create methods and functions that may deal with dynamic code. These applications ought to have the power to govern variables, properties, and object strategies at runtime. To this finish, a brand new world object, Mirror
, that’s able to dealing with easy code manipulation, was launched in ES6.
The aim of this text is that will help you higher perceive the idea of Mirror
in JavaScript and the right way to use the assorted strategies offered. Mirror
lets you simply tinker with the performance of an current object whereas nonetheless offering its default habits.
Desk of Contents:
What’s JavaScript Mirror
?
JavaScript Mirror
is an inbuilt ES6 world object that gives the power to govern properties, variables, and object strategies at runtime. It’s not a constructor, due to this fact you can not use the new
operator with it.
What’s the distinction between the Proxy
constructor and Mirror
?
Proxy
and Mirror
had been each launched in ES6 and are used for performing duties, however they’re a bit completely different.
In contrast to Mirror
, JavaScript’s Proxy
doesn’t have any properties. As a substitute, it wraps round one other object and intercepts its operations. In the meantime, Mirror
is an inbuilt object that simplifies the creation of Proxy
and makes it potential to name inner strategies.
Proxy
takes solely two arguments:
goal
: The thing that theProxy
will wraphandler
: TheProxy
configuration that can intercept goal operations
Right here’s an instance:
const profile = { identify: 'Pascal', age:23 } const handler = { get(goal, prop, receiver) { if (goal[prop]) { return goal[prop] } return `"${prop}" prop do not exist on this object !` } } const profileProxy = new Proxy (profile, handler) console.log(profileProxy.identify) // Pascal console.log(profileProxy.career) // "career" prop do not exist on this object !
The above instance is equal to Mirror.get()
, which is described later on this information, nevertheless, the Mirror.get()
approach is less complicated and extra easy.
Utilizing the JavaScript Mirror
API strategies
Let’s take a better have a look at the strategies of the Mirror
object. All of those strategies are static, i.e., they might solely be used on the Mirror
object and never on any situations.
Mirror.assemble()
The new
operator and Mirror.assemble()
technique are comparable and are just like new goal(...args)
, however with the choice to decide on a special prototype. Mirror.assemble()
accepts three arguments:
goal
: The perform to be invokedargs
: An array of argumentsnewTarget
: An non-obligatory constructor whose prototype ought to be utilized; if it isn’t specified, its default worth isgoal
Think about the next instance:
perform summation(x,y,z){ this.add = x + y +z } const sum = Mirror.assemble(summation, [1,2,3,4,5]) console.log(sum) // End result: summation {add: 6}
Mirror.assemble()
produces a brand new occasion of the goal
or newTarget
(if specified), which was constructed with the equipped array of arguments, args
. Earlier than the introduction of Mirror.assemble()
, we might mix constructor and prototype to create an object: Object.create()
.
Mirror.apply()
Mirror.apply()
is an easy and simple technique to name a goal perform utilizing the offered parameter. It takes in three parameters:
goal
: The perform to be invokedthisArgument
: Thethis
worth is required to invoke thegoal
performargs
: An array containing the parameters with whichgoal
ought to be invoked
Right here’s an instance:
/* Return the best worth within the array */ const arr = [3,5,20,3,31] const a = Mirror.apply(Math.max, undefined, arr) console.log(a) // End result: 31
Earlier than Mirror.apply()
was launched, we may use the perform.prototype.apply()
technique to carry out the same job, like so:
const arr = [3,5,20,3,31] const a = Perform.prototype.apply.name(Math.max, undefined, arr); console.log(a) // End result: 31
Mirror.defineProperty()
To create or edit a property on an object, use the Mirror.defineProperty()
technique. It returns a Boolean worth that signifies whether or not a property was efficiently outlined. This technique takes three parameters:
Extra nice articles from LogRocket:
goal
: The thing on which the property might be outlinedpropertyKey
: The identify of the property to create or editattributes
: The attributes of the properties which are being outlined
See the next instance:
const obj = {} Mirror.defineProperty(obj, 'prop', {worth: 70}) console.log(obj.prop) // End result: 70
Mirror.get()
Because the identify implies, Mirror.get()
is used to retrieve a property from an object. It accepts three arguments:
goal
: The thing to be focusedpropertyKey
: The identify of the property to acquirereceiver
(non-obligatory): If a getter is encountered, thethis
worth is handed because the receiver for the decision to the goal object
Right here’s an instance:
// with array const b = [10,11,12,13,14] console.log(Mirror.get(b, 2)) // End result: 12 // with object const obj = {identify: "Pascal", age: 23} console.log(Mirror.get(obj, 'age')) // End result: 23
Mirror.getPrototypeOf()
The Mirror.getPrototypeOf()
perform returns the prototype of the offered goal, very like Object.getPrototypeOf()
. Just one argument is accepted by this technique:
goal
: The thing of which we need to get the prototype
See the next instance:
const profile = { identify: 'Pascal' }; const professional = Mirror.getPrototypeOf(profile); console.log(professional);
Mirror.set()
The Mirror.set()
technique is used to assign a price to an object property. It returns true
to point that the property was set efficiently. This perform takes 4 arguments:
goal
: The thing on which the property is to be setkey
: The property’s identifyworth
: The worth that might be allottedreceiver(non-obligatory)
: If a setter is discovered, thethis
worth have to be used to name the goal
Right here’s an instance:
const arr1 = []; Mirror.set(arr1, 0, 'first'); Mirror.set(arr1, 1, 'second'); Mirror.set(arr1, 2, 'third'); console.log(arr1);
Mirror.deleteProperty()
Mirror.delete Property()
is a technique for eradicating a property from an object. If the property is accurately deleted, it returns true
. This perform takes two arguments:
goal
: The thingke
y: The identify of the property to be deleted
See the next instance:
Mirror.deleteProperty(obj3, 'age'); console.log(obj3)
Mirror.isExtensible()
Mirror.isExtensible()
, like Object.isExtensible()
, is a technique that detects if an object is extensible (i.e., whether or not further properties could also be added to it). Mirror.isExtensible()
returns a Boolean to point whether or not the goal is extensible. It solely considers one argument:
goal
: The thing to be checked for extensibility
The Mirror.preventExtensions()
technique could also be used to forestall an object from changing into extensible i.e prevents new properties from ever being added to an object.
See the beneath instance:
const consumer = { identify: "John Deeman" }; console.log(Mirror.isExtensible(consumer)) // true // block extension Mirror.preventExtensions(consumer); console.log(Mirror.isExtensible(consumer)) // false
Mirror.ownKeys()
The Mirror.ownKeys()
technique mainly returns an array containing the property keys of the goal object. It solely considers one argument:
goal
: The thing from which to get the keys
Right here’s an instance:
const obj = { automotive: "Rolls Royce", colour: "black" }; const array1 = []; console.log(Mirror.ownKeys(obj)); // ["car", "color"] console.log(Mirror.ownKeys(array1)); // ["length"]
Mirror.getOwnPropertyDescriptor()
The Mirror.getOwnPropertyDescriptor()
technique returns a descriptor that defines how a particular property on a given object is configured. It requires two parameters:
goal
: The thing to be looked for the propertykey
: The identify of the property for which an outline is required
See the beneath instance:
const obj = { automotive: "Rolls Royce", colour: "black", get (){ return `I've a ${colour} ${automotive} automotive` } }; console.log(Mirror.getOwnPropertyDescriptor(obj, 'automotive').worth); // "Rolls Royce" console.log(Mirror.getOwnPropertyDescriptor(obj, 'colour')); // {worth: "black", writable: true, enumerable: true, configurable: true} console.log(Mirror.getOwnPropertyDescriptor(obj, 'colour').writable); // true
A property descriptor could include the next attributes:
worth
: The worth related to the propertywritable
: A Boolean that returnstrue
provided that the property’s related worth is modifiableconfigurable
: A Boolean that returnstrue
provided that the property descriptor’s sort could also be modified and the property might be faraway from the associated objectenumerable
: A Boolean that returnstrue
provided that the property seems throughout property enumeration on the associated object
Mirror.has()
The Mirror.has()
technique verifies if a property is outlined within the goal object. It returns a boolean. Mirror.has()
performs related operations to the in
operator and accepts two parameters:
goal
: The thing to which the property might be checkedkey
: The identify of the property to confirm
Right here’s an instance:
const obj = { identify: "Douglas" }; console.log(Mirror.has(obj, 'identify')); // true console.log(Mirror.has(obj, 'age')); // false console.log(Mirror.has(obj, 'toString')); // true
Conclusion
On this article, we examined the JavaScript Mirror
object and likewise mentioned the distinction between Proxy
and Mirror
. We additionally checked out examples of the right way to use numerous Mirror
strategies, together with Mirror.get()
for returning the worth of an object property, Mirror.deleteProperty()
for deleting an object’s property, and Mirror.ownKeys()
for returning an object’s property keys.
LogRocket: Debug JavaScript errors extra simply by understanding the context
Debugging code is all the time a tedious job. However the extra you perceive your errors the better it’s to repair them.
LogRocket lets you perceive these errors in new and distinctive methods. Our frontend monitoring resolution tracks consumer engagement along with your JavaScript frontends to provide the skill to search out out precisely what the consumer did that led to an error.
LogRocket data console logs, web page load instances, stacktraces, gradual community requests/responses with headers + our bodies, browser metadata, and customized logs. Understanding the influence of your JavaScript code won’t ever be simpler!