Javascript对象方法未定义
javascript object method undefined
所以,我是新的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
关键字。
相关文章:
- 骨干's Router.execute(callback,args,name)方法获取未定义的名称
- React路由器错误-'无法调用方法'getRouteAtDepth'的未定义'
- 使用javascript ajax post方法的未定义偏移PHP错误
- 在不兼容的接收器上调用的方法Set.prototype.add未定义
- PhoneGap无法调用未定义的方法loadurl
- jQuery验证器添加方法未定义
- Backbone中未定义的方法
- JS方法显示了未定义的简单示例
- TinyMCE验证给出错误:无法调用方法'getContent'的未定义
- 获取“;无法读取属性'[方法]'“未定义”;
- 续集返回未定义的模型自定义方法
- NoMethodError ('admin_application_path'的未定义方法)
- 理解modal.js中的未定义方法
- 带有base64的回形针:#<字符串:0xb46dba14>的未定义方法“stringify_keys”
- Rails 为 nil:NilClass 创建动作未定义方法 'each'
- 方法错误:未定义方法名称
- 在laravel 5.3中调用未定义方法IlluminateDatabaseQueryBuilder::attac
- addEventListener有无法解释的未定义方法错误
- 无法设置未定义方法的属性
- 带有ECMAScript6的JSHint:未定义方法