Encountered a peculiar array anomaly when used within a class... Attempted to unravel the mystery, but couldn't quite grasp it. So here's what went down.
class weirdArray{
constructor(){
this.array=[0,2,3];
this.fn=this.fn.bind(this);
}
fn(){
console.log(this.array.slice(0,this.length));// will print [0,2,3]
console.log(this.array.slice(0,this.length-1));// will print an empty array
}
}
const obj=new weirdArray();
obj.fn();
It functions perfectly when attempting to access the entire array using this.array.slice(0,this.length)
. It returns the complete array. However, upon trying to retrieve an array without the last element with
this.array.slice(0,this.length-1)
, instead of the expected output, an empty array is returned. This issue seems to only arise within a method of an object. The expected behavior is exhibited under normal circumstances.
const array=[0,2,3];
console.log(array.slice(0,this.length-1)); // will print [0,2]
Even after removing the bind
method to test its impact on the behavior, the result remains constant...
Any insights as to why this phenomenon occurs?