原型功能声明

问题描述 投票:0回答:3

我已经定义了功能:

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);
   }

}

如您所见,我定义了三个 原型函数:getColor()createCar()getCar()

内部createCar()函数,我称之为getColor()

在函数getCar()中,我将this.createCar用作CarFactory构造函数的参数。我收到了错误:

this.getColor不是函数

在上述位置,为什么会出现此错误?如何摆脱这个错误?

javascript prototype javascript-framework
3个回答
3
投票

我认为您可能没有制作Test对象并正确调用它。我将您的代码段粘贴到测试页中,然后添加:

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

...替换console.log(color);显示我的测试中正确的结果为“红色”。

http://jsfiddle.net/2F5zz


0
投票

如果正确实例化Test。像这样:

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

您不会收到此错误。在我看来,您正在尝试通过以下方式致电createCar

Test.createCar();

定义原型时,您正在定义将被复制到该类型/功能的任何实例的成员。在您的情况下,您要定义每个Test实例将具有2个函数,即getColor和createCar。因此,这些功能不在测试范围内。它们属于Test实例的范围。您使用键盘new

创建实例

0
投票

因为有this.createCar作为回调,所以您只传递了没有上下文的函数。

尝试如下更改您的代码:

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

或者只是将Test实例传递给CarFactory并将createCar的调用委托给它:P

© www.soinside.com 2019 - 2024. All rights reserved.