首页 > 解决方案 > 如何引用和计算 Javascript 对象的其他部分?

问题描述

我正在尝试从该对象的 l、w、h 属性中计算基本体积,该对象cubeitem.

var item = new Object();
    
item["cube"] = {
    dimensions: [1.00,2.00,1.50, "in"], // l, w, h, unit (inches)
    volume: (this.dimensions[0] * this.dimensions[1] * this.dimensions[2]) // V = l * w * h
};

alert( item["cube"].volume + item["cube"].dimensions[3] ); // Volume + unit (inches)

我也尝试this在计算体积时不使用,而是指定对象的确切部分:item["cube"][dimensions][0] * item["cube"][dimensions][1] * item["cube"][dimensions][2].

目标是获得警报3.00in3in. 关于我做错了什么以及这是否可行的任何建议?我可以将函数放入对象中吗?

编辑:添加实际功能:

var item = new Object();

function calcVolume (l,w,h) {
	return l * w * h;
};

item["cube"] = {
    dimensions: [1.00,2.00,1.50, "in"], // l, w, h, unit (inches)
    volume: calcVolume(this.dimensions[0],this.dimensions[1],this.dimensions[2]) // V = l * w * h
};

alert( item["cube"].volume + item["cube"].dimensions[3] ); // Volume + unit (inches)

标签: javascript

解决方案


您可以getter为此使用 a 。

var item = new Object();
function calcVolume (l,w,h) { return l * w * h;};

item["cube"] = {
    dimensions: [1.00,2.00,1.50, "in"], // l, w, h, unit (inches)
    get volume() { return calcVolume(this.dimensions[0],this.dimensions[1],this.dimensions[2]) }
};

alert( item["cube"].volume + item["cube"].dimensions[3] ); // Volume + unit (inches)

虽然我认为这将是ES6 类的一个很好的例子:

class Cube {
  constructor(l, w, h, unit) {
    this.l = l;
    this.w = w;
    this.h = h;
    this.unit = unit || "in";
  }
  get volume() { return this.l * this.w * this.h };
  get volumeAsString() { return this.volume + this.unit };
}

var c = new Cube(1.00, 2.00, 1.50);
console.log(c.volumeAsString);


推荐阅读