Search code examples
javascriptprototypeprototype-programming

Prototype declared function is not a function


var AnArray=(function(){
    var anArray=[];

    AnArray.prototype.getAnArray=function(){
        return anArray;
    }

    AnArray.prototype.setArray=function(id,val){
        anArray[id]=val;
    }
});

var objAnArray=new AnArray();

console.log(objAnArray.getAnArray());

When I try to call objAnArray.getAnArray(); it returns that it is not a function

However this below works fine

var Index=(function(){
    var Index=1;

    Index.prototype.getIndex=function(){
        return Index;
    }
    Index.prototype.setIndex=function(val){
        Index=val;
    }
});

var objIndex=new Index();

console.log(objIndex.getIndex());

Are prototypes unable to return arrays?


Solution

  • You're using anArray as an object, not an array. Use:

    this.anArray = {}; // not []
    

    Also your code looks weird. You declare the prototype in the constructor. Declare it like this instead:

    function AnArray() {
        this.anArray = {};
    }
    
    AnArray.prototype.getArray=function(){
        return this.anArray;
    }
    
    AnArray.prototype.setArray=function(id,val){
        this.anArray[id]=val;
    }
    

    In your constructor you redeclare the prototype and bind the private variable anArray in every instance to the last instance of AnArray.

    Same with Index.

    This demonstrates the bad behaviour:

    var AnArray=(function(){
        var anArray={};
    
        AnArray.prototype.getArray=function(){
            return anArray;
        }
    
        AnArray.prototype.setArray=function(id,val){
            anArray[id]=val;
        }
    });
    var a = new AnArray();
    var b = new AnArray();
    a.setArray("foo", "bar");
    b.getArray(); // { foo: "bar" }