2017-03-08 46 views
0

这可能是一个非常基本的问题,但我对Javascript很陌生,我甚至不知道我应该搜索哪个关键字来找到它。如果这个问题已经被问到,我很抱歉,请让我知道它是哪个问题。如何在使用Javascript时更新值保留在闭包中?

我读过getter和setter不能在原型中声明,所以我试图测试如果我在原型中声明getter和setter会发生什么。但是我面临另一个问题。

这是一个简单的代码,声明一个构造函数来使对象'Rectangle',它包括getter和setter。但是当我运行这段代码时,运行getArea()会得到'35',尽管我使用setWidth()将宽度值改为10。我检查了控制台上的宽度值,但它说宽度更改为10.

所以我猜这是关于闭包的东西,getArea()在声明时加载宽度和高度,并且它没有更新为我设定的价值。

1)当我更改setter的高度和宽度值时,如何更新getArea()中的值? (如何使用函数更新值来计算面积?当然我仍然想封装它,所以宽度和高度不会是这个宽度和this.height)

2)如果我对关闭的直觉是直觉错,为什么getArea()会一直吐在我脸上?

3)我想先试一下,为什么我不能在原型中声明getter和setter?

function Rectangle(w, h) { 
var width = w; 
var height = h; 

this.getWidth = function() { 
    return w; 
}; 
this.getHeight = function() { 
    return h; 
}; 
this.setWidth = function(w) { 
    if (w < 0) { 
     throw 'width cannot be under 0'; 
    } else { 
     console.log('width = w'); 
     width = w; 
     console.log('I put : ' + w); 
     console.log('width = ' + width); 
    } 
}; 

this.setHeight = function(h) { 
    if (h < 0) { 
     throw 'height cannot be under 0'; 
    } else { 
     console.log('height = h'); 
     height = h; 
    } 
}; 
} 
Rectangle.prototype.getArea = function() { 
    return this.getWidth() * this.getHeight(); 
}; 

var rectangle = new Rectangle(5, 7); 
rectangle.setWidth(10); 

alert('AREA : ' + rectangle.getArea()); 

回答

1

你必须返回“宽度”,而不是“W” 。在这里,我已经改变了你的代码进行检查,

 this.getWidth = function() { 
      return width; 
     }; 
     this.getHeight = function() { 
      return height; 
     }; 

function Rectangle(w, h) { 
 
      var width = w; 
 
      var height = h; 
 

 
      this.getWidth = function() { 
 
       return width; 
 
      }; 
 
      this.getHeight = function() { 
 
       return height; 
 
      }; 
 
      this.setWidth = function (w) { 
 
       if (w < 0) { 
 
        throw 'width cannot be under 0'; 
 
       } else { 
 
        console.log('width = w'); 
 
        width = w; 
 
        console.log('I put : ' + w); 
 
        console.log('width = ' + width); 
 
       } 
 
      }; 
 

 
      this.setHeight = function (h) { 
 
       if (h < 0) { 
 
        throw 'height cannot be under 0'; 
 
       } else { 
 
        console.log('height = h'); 
 
        height = h; 
 
       } 
 
      }; 
 
     } 
 
     Rectangle.prototype.getArea = function() { 
 
      return this.getWidth() * this.getHeight(); 
 
     }; 
 

 
     var rectangle = new Rectangle(5, 7); 
 
     rectangle.setWidth(10); 
 

 
     alert('AREA : ' + rectangle.getArea());

0

你消气剂返回wh你已经通过了,而不是本地关闭的widthheight变量。然后,您在设置者中设置此widthheight,但原始wh仍保留其初始值,并在您的获取者中返回。

尝试更新你的两个getter函数来回报您的widthheight如果你想让他们回到你在setter方法使用更新的值:

this.getWidth = function() { 
    return width; 
}; 
this.getHeight = function() { 
    return height ; 
}; 
+0

...!我应该让我的Javascript书的作者知道他的书上有一个错字。改变getter后,它一切正常。谢谢! – HyeonWoo

+0

@HyeonWoo很乐意帮忙。如果这能解决您的问题,请不要忘记标记为已回答! – rgthree

+0

对不起,我在哪里可以找到标记为已回答的按钮?我是全新的 – HyeonWoo

相关问题