为什么这个对象不起作用

Why's this object not working?

本文关键字:不起作用 对象 为什么      更新时间:2023-09-26
box = new Object();
box.height = 30;
box.length = 20;
box.both = function(box.height, box.length) {
    return box.height * box.length;
}
document.write(box.both(10, 20));

正如标题所说。

首先,我创建了一个对象。根据特性、高度和长度制造。为每个分配了一个值。做了一个方法在函数中,我会放置 2 个参数,它们是对象属性。退回了他们的产品。最后调用函数给它数值。

为什么这不起作用:(

问题是:

box.both=function(box.height,box.length){

box.heightbox.length 不是函数参数的有效名称。 这应该是:

box.both=function(h, l) {
   return h * l;
}

但是,您似乎希望获取当前盒子实例的区域。 在这种情况下,您不需要任何参数:

box.both=function() {
   return this.height * this.length;
}
document.write(box.both());

我想你可能想要这样:

box = new Object();
box.height = 30;
box.length = 20;
box.both = function(height,length){
    this.height = height;
    this.length = length;
    return height*length;
}
document.write(box.both(10,20));
box = new Object();
box.height = 30;
box.length = 20;
box.both = function() {
    return box.height * box.length;
}