Search code examples
javascriptobjectconstructorprototypeiife

Why can't I call a method on the prototype?


I am trying to create a JavaScript object constructor within a closure, and then return the constructor so that I can create this object without any conflicts with other JS libraries.

Consider this code:

Test = (function(){

    var T = function(){
        this.x = 0;
    }

    T.prototype.doSomething = function(){
        this.x = 10;
    }

    return T;

});
var test = new Test();
test.doSomething(); 
alert(test.x);

Why is it that test.doSomething() is not a function, when I have defined it in the prototype?


Solution

  • You're not creating an instance of the right function! If you look at Test:

    var Test = (function() {
      //...
      return T;
    });
    

    Here, you're assigning Test to function that returns T, not T itself! That's why you can't call a method on the prototype of T. Instead, use an IIFE:

    var Test = (function() {
    
    })(); //Important!
    

    This will assign T's reference to Test. Then create a new instance:

    new Test();