所以,我是JS的新手,我有一些對象方法的問題。 建築物對象原型中的方法buy()應該做我爲之定義的方法,但它會顯示「未定義」。javascript對象方法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」,但沒有任何反應。哪裏不對?
編輯:我的新代碼:
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");
您不明白javascript是如何工作的,請閱讀該書:http://eloquentjavascript.net/並重試。如果您對其核心概念沒有基本的瞭解,則不能使用該語言。 – mpm