zuza29
November 25, 2022, 10:10pm
1
Hi everybody,
I’ve completed the JS challenge ‘Mysterious Organism’ and everything works. However, I would like to optimise my code by using callbacks in the object methods, instead of writing the whole functions inside the actual object methods. I can’t understand how to create callbacks that use ‘this’ so that everything works as it should (aka ‘this’ correctly refers to the proper object). I’d be grateful for any help.
This is my code on codepen:
https://codepen.io/zuza29/pen/gOKzyKP
I’m not sure if I can link this project’s guidelines somehow, so I’m just gonna link its thread on the forums:
https://discuss.codecademy.com/t/mysterious-organism-challenge-project-javascript/462376
Thank you!
You can create a function outside an object that uses this
and assign it as a property of the object.
Your code:
const pAequorFactory = (num, arr) => {
const obj = {
specimenNum: num,
dna: arr,
mutate() {
mutateFn(this.dna);
},
compareDNA(object) {
let comp1 = this.dna;
let comp2 = object.dna;
let totalNum = 0;
for (i = 0; i < comp1.length; i++) {
for (j = 0; j < comp2.length; j++) {
if (comp1[i] === comp2[j]) {
totalNum++;
}
}
}
const percentage = (totalNum / comp1.length).toFixed(2) + "%";
return percentage;
},
You could have also done:
function mutate() {
mutateFn(this.dna);
}
function compareDNA(object) {
let comp1 = this.dna;
let comp2 = object.dna;
let totalNum = 0;
for (i = 0; i < comp1.length; i++) {
for (j = 0; j < comp2.length; j++) {
if (comp1[i] === comp2[j]) {
totalNum++;
}
}
}
const percentage = (totalNum / comp1.length).toFixed(2) + "%";
return percentage;
}
const pAequorFactory = (num, arr) => {
const obj = {
specimenNum: num,
dna: arr,
mutate: mutate,
compareDNA: compareDNA,
Notice that I used
function compareDNA(object) {
instead of
const compareDNA = (object) => {
so that the this
keyword works appropriately.