gpt4 book ai didi

javascript 对象方法未定义

转载 作者:行者123 更新时间:2023-11-28 19:55:09 25 4
gpt4 key购买 nike

所以,我是 JS 新手,我在对象方法方面遇到了一些问题。构建对象原型(prototype)中的方法 buy() 应该执行我为其定义的操作,但它显示“未定义”。

var bitcoins=9000; //for example
var bitcoinsps=0;
function building(price, bps, name) {
this.price = price;
this.bps = bps;
this.name = name;
this.amount = 0;
}
building.prototype.buy = function buy() {

if (bitcoins >= building.price) {
amount++;
bitcoins -= price;
price *= 1.15;
bitcoinsps += bps;
}
};

注意:是的,我确实创建了一个实例。

我在调用变量时尝试了“building.blabla”和“this.blabla”,但没有任何反应。怎么了?

编辑:我的新代码:

var bitcoins = 0;
var bitcoinsps = 0;
var build = new Array();

function building(price, bps, name) {
this.price = price;
this.bps = bps;
this.name = name;
this.amount = 0;

}
building.prototype.buy = function() {

if (bitcoins >= building.price) {
this.amount++;
bitcoins -= this.price;
this.price *= 1.15;
bitcoinsps += this.bps;
}
};
build[1] = new building(70, 1, "Junky laptop");
build[2] = new building(300, 4, "Average PC");
build[3] = new building(1000, 15, "Gaming PC");
build[4] = new building(5000, 70, "Dedicated Hardware");
build[5] = new building(24000, 300, "Small cluster computer");
build[6] = new building(100000, 1000, "Medium cluster computer");
build[7] = new building(500000, 4500, "Large cluster computer");

最佳答案

buy() 必须使用this.blabla。因此,像这样改变它的实现:

building.prototype.buy = function buy() {
if (bitcoins >= this.price) {
this.amount++;
bitcoins -= this.price;
this.price *= 1.15;
bitcoinsps += this.bps;
}
};

此外,您必须使用“new”创建一个建筑实例。例如:

var b = new building(1, 2, 'fred');
b.buy();

关于javascript 对象方法未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22725936/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com