开发者

Prototype function declaration

开发者 https://www.devze.com 2023-02-27 06:24 出处:网络
I have defined the function: var Test = function(){ }; Test.prototype={ getColor: function(){ return \"red\";

I have defined the function:

var Test = function(){

};

Test.prototype={

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

   createCar: function(){
      var color = this.开发者_如何学PythongetColor(); //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?


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


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消