我已经定义了函数:
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);
}
}
如您所见,我定义了三个 原型(prototype)函数:getColor()、createCar() 和getCar()。
在createCar()函数中我调用了getColor(),
在函数getCar()中,我使用this.createCar作为CarFactory构造函数的参数。我收到错误:
"this.getColor is not a function"
在上面指出的地方,为什么会出现这个错误?如何消除这个错误?
最佳答案
我认为您可能没有创建 Test
对象并正确调用它。我将您的代码片段粘贴到测试页面中,然后添加:
var obj = new Test();
console.log(obj.getColor());
// Outputs 'red'
obj.createCar();
// Does not throw an error.
用 console.log(color);
替换 ...
在我的测试中显示了正确的结果“红色”。
关于javascript - 原型(prototype)函数声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5702780/