javascript - JavaScript 中的对象属性 "Previous Value"

标签 javascript variables object oop

我刚刚开始思考整个面向对象的事情,所以请耐心等待。

所以,我看到了一个对象函数(针对 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/

相关文章:

javascript - 将带有 $currentDate 的字段插入 Meteor 中的 MongoDB 集合

javascript - Chrome Tab重复项未发出网络请求

javascript - 如何将随机数附加到字符串?

javascript - 如何通过单击按钮打开 Accordion 菜单?

python - 为什么我可以覆盖类变量?指针被覆盖?

php - 如何在不知道其名称的情况下访问 JSON 对象(并且不在数组中)

javascript - Javascript 中基本原型(prototype)设计的问题

javascript - 添加 Javascript 变量

php - 如何让 phpmailer 发送给正确的用户并限制某些用户的电子邮件数量?第2部分

java - 让物体变得更简单、更干净