I'm studying JavaScript and jQuery and I did an implementation of a simple cat clicker game:
class Cat {
constructor(name, picture) {
let self = this;
self.name = name;
self.picture = picture;
self.count = 0;
let mainDiv = $('#cats');
let catDiv = $('<div></div>');
mainDiv.append(catDiv);
self.img = $(`<img src="${self.picture}">`);
catDiv.append(self.img);
self.counter = $('<p></p>');
catDiv.append(self.counter);
self.img.click(function() {
self.count++;
self.counter.text(`You clicked ${self.name} ${self.count} times.`);
self.counter.css("font-size", "+=0.5");
});
}
}
$(document).ready(function() {
new Cat('Kimmy', 'http://newmediarockstars.com/wp-content/uploads/2014/07/femcat.png');
new Cat('Logan', 'http://svoctopussy.com/wp-content/uploads/2013/02/Grumpy-Cat.jpg');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<h1>Cat Clicker</h1>
<div id="cats"></div>
I wanted it to be dynamic, so if I want to add more cats, I just have to instance a new object of the Cat
class, like it's done in the document.ready
function.
The Cat
constructor adds a new cat in the HTML (it appends the cats
div), using div
, h1
, img
and p
. Everytime you click the img
(🐱), the p
element text is updated with the click count.
I'm a complete beginner in JS. What can I refactor here to make the code more legible and idiomatic?
EDIT: In the third line, there's a let self = this;
. I did that because I needed to access the Cat
instance inside the img.click
callback function. I don't know if that's how it's done nor how I can improve that.