我正在尝试调用游戏中对象的方法,但不断收到此错误:"未捕获的类型错误:对象 # 没有方法'计算Dps'",这是相关代码:
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(){
...
但理想的方法是将函数添加到原型中,如下所示
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
。