Search code examples
javascriptoopprototype

JavaScript prototype array member cannot find push of undefiend


I am trying to implement a stack. when I try to push into the arr this error pops up

TypeError: Cannot read property 'push' of undefined

var MinStack = function() {
    let Min = null;
    const arr = new Array(); // I also tried arr = []
};

/** 
 * @param {number} x
 * @return {void}
 */
MinStack.prototype.push = function(x) {
    this.arr.push(x);
    this.Min = Math.min(...arr);
};

I searched for answers but I didn't find out why can't I access my arr in the constructor?


Solution

  • This is because this.arr is not defined.

    You have defined the arr as a variable as you have used let to declare it, but not as a property of the instances of MinStack.

    Variables declared using let or const are scoped to the enclosing block and not available outside of it.

    The enclosing block in your case the function block, so it becomes a local variable scoped to the function and not visible outside of it.

    When you use a function as a constructor and use the new keyword to instantiate it a new object is created in memory and is assigned to the this reference in the constructor function. properties assigned to that this reference become properties of the instance created from the constructor function:

    var MinStack = function() {
        this.Min = null;
        this.arr = new Array(); 
    };
    
    /** 
     * @param {number} x
     * @return {void}
     */
    MinStack.prototype.push = function(x) {
        this.arr.push(x);
        this.Min = Math.min(...this.arr);
    };
    
    MinStack.prototype.min = function(x) {
        return this.Min;
    };
    
    const minArr = new MinStack();
    minArr.push(1);
    minArr.push(2);
    minArr.push(3);
    minArr.push(-9);
    console.log(minArr.min());