Extending Built-In Data Types with JavaScript

preview_player
Показать описание
In today's we'll explore the idea of extending built-in data types with JavaScript. It's worth noting that there are differing opinions online on whether or not you should do this for your project.

It's easy to "add" functionality to built-in types such as a JavaScript array - you can do things like react to when new items are added to the array, and update the user interface.

If this video helped you out and you'd like to see more, make sure to leave a like and subscribe to dcode!

#dcode #javascript
Рекомендации по теме
Комментарии
Автор

What a really cool idea. I love finding new little ideas like this. Previously I would have wrapped this in some pushToArray function that manually calls the handler after, but extending the basic class is a really neat little trick.

Thanks for sharing, Dom!

robwatson
Автор

Great video mate, like always...

If you don't use classes and you want to make the method generic (any element, any array) you could also do this:

Array.prototype.listPush = function(id, ...args){
this.push(...args);
let element = document.getElementById(id);
if(element){
let frag =
for(let i of this){ = i;}
element.replaceChildren(frag)
}
return this
}

And if you "return this" it also means you can chain a splice to clear the array on the end e.g.
someArray.listPush('someID', 1, 2, 3, ).splice(0, someArray.length)

On a side note calling an onPush() function indirectly has a huge performance hit the first/ second time its called.... at least the last time I tested it (a few years ago), so it might be worth just making alternative methods instead of modifying push.

The video was pretty informative. As somebody who doesn't use classes much (except custom-elements) I wasn't aware that super.push() could be called inside a modified push() method.

Thanks again for a great video

cloudpuncher
Автор

Thank you so much, it's really a good tip for self altering content without refreshing the pages

hassaneoutouaya
Автор

Last time I did this it was to fire a nodejs event every time an item was added or removed from the array. It was extremely useful, never thought about using it for something on the frontend though.

jordanski
Автор

Why you shouldn't use it in production? You're creating a new subclass ObservableArray, which doesn't affect the original Array class, so Array.push should be the same, right?

testkj
Автор

wouldn't it be better to use Proxy?

lordcrasty