0

考虑以下代码:

function rectangle(x, y) {
    this.width = x;
    this.height = y;
    this.calcArea = function() {
        return (this.width * this.height);
    };
}

rectangle对象有两个属性(宽度和高度)和一个方法(calcArea)。

我希望向矩形对象添加另一个属性:area. 我将通过原型方法做到这一点,如下所示:

rectangle.prototype.area = function () {return this.calcArea();}

现在想象一下,我们创建了一个新的矩形实例:var r = new rectangle(2,3); 不幸的是,area它是一个方法。要检索正确的值,您必须调用r.area();

由于area应该(至少在语义上)是属性而不是方法,有没有办法直接将结果分配给calcArea()属性r.area

如果我将原型更改为:

rectangle.prototype.area = function () {this.area = this.calcArea();}

我必须打r.area()一次电话,然后所有随后的电话都r.area将是一个号码,根据需要。这还不错,但并不完美。那么有没有更好的方法呢?

4

3 回答 3

2

矩形的面积是根据其他属性计算得出的,这些属性从一个矩形变为另一个矩形。因此,区域不属于原型,而是属于每个实例。无论如何,在原型中拥有一个属性将被 Rectangle 的每个实例所掩盖是没有意义的。计算可以属于原型,因为它对于每个矩形都是相同的。

为了得到这个值,你必须至少计算一次,就像你说的那样。您可以在 Rectangle 的构造函数中执行此计算,但最好将方法留在原型中,因为它不需要复制。

function Rectangle(x, y) {
    this.width = x;
    this.height = y;
    this.area = this.calculateArea();
}

Rectangle.prototype.calculateArea = function(){
    return this.width * this.height;
}

请记住,如果您在创建矩形尺寸后更改此值,则不会更新此值。出于这个原因,我总是按需计算它,因为它更安全,除非这个属性经常被调用并且性能是一个问题。

于 2012-11-19T15:28:32.400 回答
1
function rectangle(x, y) {
    this.width = x;
    this.height = y;
    this.calcArea = function() {
        return (this.width * this.height);
    };
    this.area = this.calcArea();
}

您可以这样做,但如果您修改或this.area不会更新。但是您可以检查一下:https ://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/defineProperty 它可能会对您有所帮助。widthheight

于 2012-11-19T14:37:34.900 回答
1

为什么不在构造函数中计算呢?

function rectangle(x, y) {
    this.width = x;
    this.height = y;
    this.area = x*y;
    ..
}

现在的问题是,如果您更新widthheight. 在这种情况下使用这个。

function rectangle(x, y) {
    this.width = x;
    this.height = y;
    this.area = x*y;
    this.updateWidth = function(w){
        this.width = w;
        this.area = this.width*this.height;
    }
    this.updateHeight = function(h){
        this.height = h;
        this.area = this.width*this.height;
    }
}
于 2012-11-19T14:38:04.057 回答