S
S
Sergey2018-02-18 16:17:20
JavaScript
Sergey, 2018-02-18 16:17:20

How to overload metamethods in JS?

In Lua, objects have metatables that contain metamethods - functions called when working with objects, in fact, these are object methods, for example, adding a new element to an array, these metamethods can be overloaded ... It is interesting that there are metamethods that are not called only when a method or property of an object is explicitly called, but also with some other events, such as object initialization, access to an array element, etc... In JS, I need to catch the moment when a value is added to the array, not only through the method (s)

var arr = [];
arr.push("string");

but also with a syntactic construction:
var arr = [];
arr[1] = "string";

Tell me how you can catch and overload methods on objects in JS?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2018-02-18
@Graff46

Proxy - this is so that you can process

arr[1] = "string"

You make a set trap - there are examples on the link.
catch and overload methods

You can replace the old method with a new one, inside which there will be a call to the old one (if necessary) + some other code of yours.
Or, as is customary in more traditional languages, you make the class an heir, where you override what you need.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question