Join devRant
Do all the things like
++ or -- rants, post your own rants, comment on others' rants and build your customized dev avatar
Sign Up
Pipeless API

From the creators of devRant, Pipeless lets you power real-time personalized recommendations and activity feeds using a simple API
Learn More
Related Rants
JavaScript keeps surprising me, or I'm just rushing. lol
class Group {
#group;
constructor(){
this.group = [];
return this.group;
}
add(item) {
// only if it isn't already a member
// value can be part of set only once
if(!this.has(item)) {
group.push(item);
}
}
has(item){
// return boolean: item member of group
for(let i=0; i<group.length; i++) {
if(group[i] === item) {
return true;
}
}
return false;
}
let group = new Group();
group.add(1);
console.log(group);
Error: group.add() is not a function
Why is group.add() not a function?
A.I. analysis:
1. Private field vs public field:
A private field #group can only be accessed as this.#group. But in the constructor, I wrote:
this.group = [];
This creates a new public field, unrelated to #group.
2. Returning from constructor:
return this.group;
In JavaScript, a constructor automatically returns this, which is the instance of the class. Returning this.group replaces the instance with the array. That’s why after new Group(), your variable group is just an array, not an instance of Group. Arrays don’t have the add method — hence the error.
3. Referencing group inside methods:
group.push(item);
Here group is not defined. You probably meant this.group (or this.#group if using the private field).
Note to self: in the magic of computer science, you must be precise. If I loosely define the black box, the result will have a chance of producing anomalies.. kind of like reality. lol
rant
javascript
not-a-function
classes
error