Javascript对象方法未定义

javascript object method undefined

本文关键字:未定义 方法 对象 Javascript      更新时间:2023-09-26

所以,我是新的JS,我有一些问题与对象方法。构建对象原型中的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;
    }
};

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

i try "building. "Blabla"answers"这个"。当调用变量时,什么也没发生。怎么了?

编辑:my new code:

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

你不需要重新声明方法名;以下代码:

building.prototype.buy = function(){
    // function body
}

将创建building对象的实例函数buy。要使用它,您需要创建一个building的实例:

var b = new building(/*params*/);
b.buy();

并且,正如cybersam指出的,使用building类的任何成员变量都需要使用this关键字。