Mellon
Mellon

Reputation: 38842

Prototype function declaration

I have defined the function:

var Test = function(){

};

Test.prototype={

   getColor: function(){
         return "red";
   },

   createCar: function(){
      var color = this.getColor(); //ERROR: this.getColor is not a function
      ...
   },

   getCar: function(){
      return new CarFactory(1, this.createCar);
   }

}

As you saw, I have defined three prototype functions: getColor() , createCar() and getCar().

Inside createCar() function I called getColor(),

In function getCar(), I use this.createCar as a parameter of CarFactory constructor. I got the error:

"this.getColor is not a function"

in the above indicated place, why this error? How to get rid of this error?

Upvotes: 0

Views: 133

Answers (3)

Francesco Terenzani
Francesco Terenzani

Reputation: 1391

Because with this.createCar as callback you are passing just the function without its context.

Try to change your code as follow:

   getCar: function(){
      var that = this;
      return new CarFactory(1, function() {
            return that.createCar();
      });
   }

Or just pass the Test instance to CarFactory and delegate to it the calling of createCar :P

Upvotes: 0

Andre Pena
Andre Pena

Reputation: 59336

If you instantiate Test correctly. Like this:

var test = new Test();
test.createCar(); 

You won't get this error. It seems to me that you are trying to call createCar this way:

Test.createCar();

When you define prototypes you are defining members that will be copied to any instance of that type/function. In your case, you are defining that every instance of Test will have the 2 functions, getColor and createCar. So, these functions are not on the Scope of Test. They are on the scope of instances of Test. You create instances with keywork new

Upvotes: 0

Jim Blackler
Jim Blackler

Reputation: 23169

I think you might not be making a Test object and invoking it properly. I pasted your snippet into a test page, then added:

var obj = new Test();
console.log(obj.getColor());
// Outputs 'red'
obj.createCar();
// Does not throw an error. 

Replacing your ... with console.log(color); revealed the correct result 'red' in my test.

http://jsfiddle.net/2F5zz

Upvotes: 3

Related Questions