learnjavascript
-
Self Learning: Harry tries this code to toggle a CSS class when a button is clicked, but it doesn’t work. Why?
I have been reading this book "Modern Javascript for the Impatient", chapter "Object-Oriented Programming". At the end there is an "Exercise" section. This is a question from it I need help answering:
*** Harry tries this code to toggle a CSS class when a button is clicked:
const button = document.getElementById('button1') button.addEventListener('click', function () { this.classList.toggle('clicked') })
It doesn’t work. Why?
Sally, after searching the wisdom of the Internet, suggests:
button.addEventListener('click', event => { event.target.classList.toggle('clicked') })
This works, but Harry feels it is cheating a bit. What if the listener hadn’t produced the button as event.target? Fix the code so that you use neither this nor the event parameter.
***
-
Self Learning: Rewrite this code in Javascript without using inheritance.
I have been reading a book on JS. This is one of the questions at the end of a chapter that stumped me; don't know where to begin. So please help me out:
Question
A classic example for an abstract class is a tree node. There are two kinds of nodes: those with children (parents) and those without (leaves).
class Node { depth() { throw Error("abstract method") } } class Parent extends Node { constructor(value, children) { . . . } depth() { return 1 + Math.max(...children.map(n => n.depth())) } } class Leaf extends Node { constructor(value) { . . . } depth() { return 1 } }
This is how you would model tree nodes in Java or C++. But in JavaScript, you don’t need an abstract class to be able to invoke n.depth().
Rewrite the classes without inheritance and provide a test program.
So, how to write this code without using inheritance in JS?
-
Tricks to learn coding fast
qvault.io Top 8 Tricks to Learn Coding FastThe journey to becoming a gainfully employed software engineer can feel long. The good news is, you can learn smarter not harder.
-
Dannjs Neural Network Beginner Tutorial
dev.to Train a Neural Network to Count, with Javascript & DannjsCounting is pretty intuitive for us humans, not as much for neural networks. This is why you are here...