我刚刚开始思考整个面向对象的事情,所以请耐心等待。
所以,我看到了一个对象函数(针对 Javascript)的示例,您可以在其中分配一个新值,并且该值将被分配为该属性的实际值。示例:
function Meat (name, color, price) {
function newPrice (new_price) {
this.price = new_price;
}
this.name = name;
this.color = color;
this.price = price;
this.newprice = newPrice;
}
很好,花花公子。现在我可以使用 Bacon.price 或 Bacon.newprice 来指定价格。就我个人而言,这似乎是最高级别的语义,因为从功能上来说它做了同样的事情。但作为语义编码的倡导者,我不会管它。这就是我想要的:
当我更改 Bacon.price 的值时,该对象应该包含一个函数,用于自动将旧值存储在名为 oldprice 的属性中。我玩过这个,但一无所获。这是我到目前为止所尝试过的:
function Meat (name, color, price) {
function oldPrice () {
this.oldprice = this.price;
}
this.name = name;
this.color = color;
this.oldprice = oldPrice;
this.price = price;
}
///////////////////////
function Meat (name, color, price) {
this.name = name;
this.color = color;
this.oldprice = this.price;
this.price = price;
}
或多或少的变化。我认为在分配新值之前引用已经分配的值(第一次没有什么)就足够了。我知道该值(或缺少值)在分配之前存储在某处,我只是不知道如何引用它以在其被清除之前将其分配给 oldvalue 属性。
好吧,也许问题出在我的眼睛或手指上。因为我认为我在询问之前已经尝试过这些建议(我知道,我没有提到它们!)除非我真的很困惑,否则这应该可行:
function Meat(price)
{
function setPrice(price)
{
this.oldprice = this.price;
this.price = price;
}
this.price=setPrice;
}
bacon = new Meat()
bacon.price = "Expensive";
document.write(bacon.price+"<br />");
document.write(bacon.oldprice+"<br />");
bacon.price = "Cheap";
document.write(bacon.price+"<br />");
document.write(bacon.oldprice+"<br />");
但是我得到的输出是: 昂贵的 不明确的 便宜的 未定义
一切都好,直到最后一个。再说一遍,我愿意接受视力不佳和拼写错误作为根源。但我想不通。
最佳答案
当您调用 obj.newPrice(xxx);
时,这会存储它 - 我认为您在使用 obj.price = xxx;
时不能自动执行此操作
function Meat (name, color, price) {
function newPrice (new_price) {
this.oldprice = this.price
this.price = new_price;
}
this.name = name;
this.color = color;
this.price = price;
this.newprice = newPrice;
}
编辑:
正如 @Mauris 所指出的,Javascript 1.5 确实支持 getters and setters (另请参阅 here - 您可以将它们视为伪装成属性的方法。
使用这些,您的代码将如下所示:
function Meat (name, color, price) {
function newPrice (new_price) {
this.oldprice = this.price
this.price = new_price;
}
this.name = name;
this.color = color;
this.__defineSetter__("price", function(newprice)
{
this.oldprice = this.price
this.price = price;
});
}
遗憾的是,Internet Explorer 尚不支持此语法。
关于javascript - JavaScript 中的对象属性 "Previous Value",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/628030/