javascript对象方法未定义

时间:2014-03-29 01:41:23

标签: javascript methods

所以,我是JS的新手,我对对象方法有一些问题。 构建对象原型中的方法buy()应该按照我为它定义的方式执行,但是它表示" Undefined"。

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"在调用vars时,没有任何反应。怎么了?

编辑:我的新代码:

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

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

您无需重新声明方法名称;以下代码:

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

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

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

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