javascript - 使对象的所有属性可变

标签 javascript oop

我如何定义一个对象的属性,以便如果其中一个属性发生更改,所有其他属性都会自动更新。

到目前为止我已经想出了这段代码,但它不起作用:

function CreateNamed(first, last) {
    Object.defineProperties(this, {
           "firstName": {
            value: first,
            writable: true
        },
            "lastName": {
            value: last,
            writable: true
        },
            "fullName": {
            value: first + ' ' + last,
            writable: true
        }
    });
}

所以在一个新的对象被创建之后,它可以被适本地改变:

var b = new CreateNamed('Bill', 'Gates'); // Bill Gates
b.firstName = 'Paul'; // b.fullName = Paul Gates
b.lastName = 'Wood'; // b.fullname = Paul Wood
b.fullName = 'Chuck Norris' // b.firstName = Chuck, b.lastName = Norris

最佳答案

value 不是动态计算的。它不会随着对象的改变而改变。为了动态计算属性,您需要使用 get and set 定义 getter 和 setter :

get
A function which serves as a getter for the property, or undefined if there is no getter. The function return will be used as the value of property. Defaults to undefined.

set
A function which serves as a setter for the property, or undefined if there is no setter. The function will receive as only argument the new value being assigned to the property. Defaults to undefined.

function CreateNamed(first, last) {
    this.first = first;
    this.last = last;
    Object.defineProperties(this, {
           "firstName": {
           get: function() { return this.first; },
           set: function(name) { this.first = name; }
        },
            "lastName": {
           get: function() { return this.last; },
           set: function(name) { this.last = name; }
        },
            "fullName": {
            get: function () { return this.first + ' ' + this.last },
            set: function (name) {
              if (!name.match(/^[a-z]+ [a-z]+$/))
                throw new Error('I cannot parse that name')
              var parts = name.split(' ')
              this.first = parts[0];
              this.last = parts[1];
            }
        }
    });

}

var user = new CreateNamed('bob', 'smith');
document.write(user.fullName); // bob smith

user.firstName = "john"; 
document.write(user.fullName); // john smith

user.fullName = "tony brian";
document.write(user.firstName); // tony
document.write(user.lastName); // brian

关于javascript - 使对象的所有属性可变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29049739/

相关文章:

c# - 使用适用于所有继承对象的方法为基类型创建集合?

Javascript:无法真正理解函数返回

javascript - 使用 if 语句声明 const 的值

Javascript,替换为正则表达式,这种情况可以吗?

function - 延迟绑定(bind)过程的 Fortran 2003 实现是否需要相同的参数?

Python 继承输出

php - 如何在 HTTP 请求和 cli 类对象之间进行对话

java - 单例实例化创建多个对象

javascript - 保持 CSS 元素活跃

javascript - 如何在 JavaScript 中重新填充下拉字段?