我尝试向对象添加功能。为什么不起作用?结果未定义。请帮忙。
<html>
<body>
<script>
var calc = function(){
this.num1 = 5,
this.num2 = 5,
compute = function( ) {
this.result = this.num1 * this.num2;
}
};
var myObj =[];
for(var i=0; i<5; i++){myObj.push(new calc())};
//calc.compute();
document.write(myObj.compute);
</script>
</body>
</html>
答案 0 :(得分:2)
有几个直接的问题。首先,构造函数应该用样式function Calc(args)
编写,以区别于其他函数,并解决范围/上下文问题。
其次,您的方法应为this.compute
。
第三,虽然将数字添加到result
变量是合适的,但从您的其他代码中看,您似乎想要从compute
返回一些内容,但您不是。
最后,为什么要创建五个相同的对象?我已经更正了,但也在下面稍微更新了你的代码,告诉你我的意思。
function Calc(first, second) {
// assign the arguments to num1 and num2
this.num1 = first;
this.num2 = second;
this.compute = function() {
// we return the result rather than assigning it
return this.num1 * this.num2;
}
};
var myObj = [];
// here we use i and 5 as the new object parameters
for (var i = 0; i < 5; i++) {
myObj.push(new Calc(i, 5));
};
for (var i = 0; i < 5; i++) {
console.log(myObj[i].compute()); // 0, 5, 10, 15, 20
};
现在,正如deceze建议的那样,分离出方法并在原型上定义它也是一个好主意,所以你最终会得到以下代码:
function Calc(first, second) {
this.num1 = first;
this.num2 = second;
};
Calc.prototype.compute = function() {
return this.num1 * this.num2;
}
答案 1 :(得分:0)
尝试使用this
关键字将该功能与对象相关联。目前,计算功能与对象无关。
您还需要返回结果并按索引访问对象
所以正确的将是
var calc = function() {
this.num1 = 5,
this.num2 = 5,
this.compute = function() {
this.result = this.num1 * this.num2;
return this.result;
}
};
var myObj = [];
for (var i = 0; i < 5; i++) {
myObj.push(new calc())
};
//calc.compute();
document.write(myObj[0].compute());
答案 2 :(得分:-2)
--nullability
。它应该是document.write(myObj.compute);
。document.write(myObj.compute());
是myObj
类型的对象数组。所以你需要索引来访问对象的任何属性。 Calc
。myObj[0].compute()
函数中缺少return语句。您正在为compute
分配值,但不返回任何内容。我已移除this.results
并添加了results
声明。以下代码代表相同:
return