每个属性上的Javascript类设置器
我正在尝试创建一个类,该类将许多对象指定为属性。我一直坚持在这些属性上实现setter 下面是失败的例子。当我执行每个属性上的Javascript类设置器,javascript,node.js,metaprogramming,Javascript,Node.js,Metaprogramming,我正在尝试创建一个类,该类将许多对象指定为属性。我一直坚持在这些属性上实现setter 下面是失败的例子。当我执行record1.foo='bar';//record.foo现在是字符串I使用字符串覆盖属性,而不是在元素类中设置值 希望这有意义,我希望setter将值写入元素中,而不是替换它 'use strict'; const assert = require('chai').assert; class Element { constructor(name) { this.
record1.foo='bar';//record.foo现在是字符串
I使用字符串覆盖属性,而不是在元素类中设置值
希望这有意义,我希望setter将值写入元素中,而不是替换它
'use strict';
const assert = require('chai').assert;
class Element {
constructor(name) {
this.name = name;
this.value = null;
}
getValue() {
return this.value;
}
setValue(value) {
this.value = value;
}
getName() {
return this.name;
}
toString() {
return this.getValue();
}
}
class Record {
constructor() {
this.fields = ['name', 'age', 'foo'];
this.fields.forEach((field) => {
this[field] = new Element(field);
});
}
setValue(field, value) {
this[field].setValue(value);
}
getValue(field) {
return this[field].getValue();
}
}
let record1 = new Record();
record1.name.setValue('Bob');
record1.setValue('age', 42);
assert.equal(record1.getValue('name'), 'Bob');
assert.equal(record1.age, 42);
console.log('so far so good');
record1.foo = 'bar'; // record.foo is now a string
assert.equal(record1.getValue('foo'), bar);
据我所知,这就是你想要的:
class Delegator {
set foo (a) {
this._foo.value = a;
}
get foo () {
return this._foo.value;
}
constructor () {
let fields = ['foo', 'value', 'name'];
fields.forEach(fld => this[`_${fld}`] = new Element(fld));
}
}
let instance = new Delegator();
instance.foo; // returns Element's value of foo
instance.foo = 'bar'; // sets Element's value to bar
作为一种动态方式,您可以尝试以下方法:
“严格使用”;
类元素{
建造师(姓名){
this.name=名称;
this.value=null;
}
getValue(){
返回此.value;
}
设置值(值){
这个值=值;
}
getName(){
返回此.name;
}
toString(){
返回这个.getValue();
}
}
课堂记录{
构造函数(){
this.fields=['name','age','foo'];
this.fields.forEach((字段)=>{
让元素=新元素(字段);
Object.defineProperty(此字段{
设置:函数(值){
元素。设置值(值);
},
get:function(){
返回元素;
}
});
});
}
设置值(字段,值){
此[field].setValue(值);
}
getValue(字段){
返回此[field].getValue();
}
}
让record1=新记录();
record1.name.setValue('Bob');
记录1.设定值('age',42);
console.log(record1.getValue('name')='Bob');
console.log(record1.age==42);
record1.foo='bar';
log(record1.getValue('foo')='bar')
是,一个setValue
方法与setter属性不同。您需要get value
和set value
而不是getValue
和setValue
。这里也不清楚你想做什么,如何做,为什么做。@Bergi-我希望这个类的用户能够使用Record.setValue(字段,值)或直接使用record1.foo='bar'@JaredSmith是的,对不起-我意识到这个问题很模糊。我想通过record1.foo支持对元素的直接赋值(而不是用字符串值替换属性),非常感谢,这就是我想要的。使用此解决方案,我可以通过直接赋值以及使用record1.foo.sayHello()
或其他方式在元素上设置值。谢谢Jared-我更喜欢AlexScr解决方案,因为它允许我通过instance.foo.sayHello()
(或其他方式)访问元素方法而您的解决方案中,元素有一个备用名称this.\u foo
。不过我还是很欣赏你的例子