I'm not sure if this is bad code or would it be "better" to put the isPrime function in a method and then use that method inside the printSomething method?, if so how would it be possible how can i use one method inside another method?
class PrimeNumbers{
constructor(isPrime, number){
this.isPrime = isPrime;
this.succes = "succes";
this.failure = "failure";
this.number = number;
}
printSomething(isPrime){
if (!this.isPrime(this.number)) {
console.log(this.succes);
} else {
console.log(this.failure);
}
}
}
function isPrime(value) {
if (value == 1) return false;
for (let i = 2; i <= Math.sqrt(value); i ) {
if (value % i == 0) {
return false;
}
}
return true;
}
let primeTest = new PrimeNumbers(isPrime, 10)
primeTest.printSomething()
CodePudding user response:
Hopefully someone who can explain this better than me comes along. In case they don't ... you can add isPrime
as a method on PrimeNumbers
and then use it with this.isPrime()
. Here, this
refers to the current object that you're dealing with.
When you do let primeTest = new PrimeNumbers(10);
primeTest becomes an instance of PrimeNumbers, when you do primeTest.printSomething()
you're accessing the printSomething property on primeTest and calling it. Once the code is executing inside printSomething it will often need a way to refer to the object that's stored in primeTest that's what the this
keyword does; it allows you to refer to the particular instance of the object that's being dealt with when the code runs.
This page is probably much better at explaining what I've just tried to explain.
In terms of whether it's better to add to add isPrime to the class. I'm not really sure, it might depend on some other things. If you don't add it to the class it's pretty unlikely that you need to pass the function as an argument to the constructor (though there probably are reasons to do this there's probably no point if you're always passing in the same function) you can just call the function inside the class methods.
isPrime as method:
class PrimeNumbers{
constructor(number){
this.succes = "succes";
this.failure = "failure";
this.number = number;
}
printSomething(){
if (!this.isPrime(this.number)) {
console.log(this.succes);
} else {
console.log(this.failure);
}
}
isPrime(value) {
if (value == 1) return false;
for (let i = 2; i <= Math.sqrt(value); i ) {
if (value % i == 0) {
return false;
}
}
return true;
}
}
let primeTest = new PrimeNumbers(10);
primeTest.printSomething();
isPrime as function called from the class:
function isPrime(value) {
if (value == 1) return false;
for (let i = 2; i <= Math.sqrt(value); i ) {
if (value % i == 0) {
return false;
}
}
return true;
}
class PrimeNumbers{
constructor(number){
this.succes = "succes";
this.failure = "failure";
this.number = number;
}
printSomething(){
if (!isPrime(this.number)) {
console.log(this.succes);
} else {
console.log(this.failure);
}
}
}
let primeTest = new PrimeNumbers(10);
primeTest.printSomething();