我试图在游戏中调用对象的方法,但不断收到此错误:“Uncaught TypeError: Object # has no method 'calculateDps'”,以下是相关代码:
function Item(pBase, price){
this.pBase = pBase;
this.price = price;
pMultiplier = 1;
number = 0;
calculateDps = function(){
return this.pBase * pMultiplier * number;
};
};
var cursor = new Item(.1,15);
var calcDps = function(){
return cursor.calculateDps();
};
calcDps();
最佳答案
calculateDps = function(){
return this.pBase * pMultiplier * number;
};
您正在创建一个名为 calculateDps
的全局变量,因为您没有使用 var
关键字。为了将其附加到当前正在生成的对象,您需要执行以下操作
this.calculateDps = function(){
...
但理想的方法是将函数添加到原型(prototype)中,如下所示
function Item(pBase, price){
this.pBase = pBase;
this.price = price;
this.pMultiplier = 1;
this.number = 0;
};
Item.prototype.calculateDps = function() {
return this.pBase * this.pMultiplier * this.number;
};
现在,calculateDps
将可用于所有使用 Item
构造函数创建的对象。
关于javascript - 未捕获的类型错误 : Object #<Item> has no method 'calculateDps' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21820580/