关于如何在网络和StackOverflow周围的JS中获取和设置对象的嵌套属性/属性,也有问题和答案,但到目前为止没有一个适合我的问题,所以就在这里。
声明/定义对象的代码是
/**
* a dummy class for experiments
*/
module.exports = function() {
this.Delme = () => {
const attrs = {
name: '',
age: '',
addr: {
street: '',
city: '',
pin: ''
}
};
return Object.create({
set(name, value) {
if (attrs.hasOwnProperty(name)) {
console.log(`setting attrs.${name} to ${value}`);
attrs[name] = value;
return true;
} else {
console.log(`Object has no property named ${name}`);
return false;
}
},
get(name) {
if (attrs.hasOwnProperty(name)) {
return attrs[name];
} else if (attrs.addr.hasOwnProperty(name)) {
return attrs.addr[name];
} else {
return null
}
}
});
};
};
/**
* Based on some other posts I wrote this anyway,
* but I'm not sure how to use this in my object creation.
*
* function() returning an 'addr' object
*/
const Address = function() {
const _addr = {
street: '',
city: '',
pin: ''
};
return Object.create({
set(name, value) {
if (_addr.hasOwnProperty(name)) {
console.log(`setting _addr.${name} to ${value}`);
_addr[name] = value;
return true;
} else {
console.log(`Object has no property named ${name}`);
return false;
}
},
get(name) {
return _addr[name];
}
});
}
// Above function is currently not used
这是我用来测试对象创建的代码
require('../lib/delme')();
const personFactory = function (target) {
return Delme.call(target);
} ;
const george = { name: 'george' };
const person = personFactory(george);
//person.on('change', data => console.log(data));
person.set('name', 'Sam');
console.log(person.get('name'));
person.set('unknown', 'anything');
console.log(person.get('unknown'));
console.log(person.hasOwnProperty('name'));
const person9 = personFactory({name: 'Charlie', age :'27'});
console.log(person9.get('name'));
console.log(person9.set('age', '42'));
console.log(person9.get('age'));
person9.set('addr', {street:'main road', city:'somewhere', pin:'560032'});
//console.log(person9.addr.city)
console.log(person9.get('city'));
person9.set('addr[street]', '3rd Lane')
console.log(person9.get('street'));
输出为
setting attrs.name to Sam
Sam
Object has no property named unknown
null
false
setting attrs.age to 42
true
42
setting attrs.addr to [object Object]
somewhere
Object has no property named addr[street]
main road
Q.1:如何正确获取()和set()嵌套属性。我希望能够person.get('addr.street')
和person.set('addr.pin', '123456')
.目前,我只能通过在对象创建期间传递来设置整个 addr 对象。
问题 2.如何使我的类发出事件,以便我可以像person.on('change', data => console.log(data));
一样编写代码
我建议您使用 ES6 类语法而不是原型并实现 set 和 get as 方法。对于问题2,没有简单的方法可以做到这一点。您可以使用 pubsub-js 等库手动实现它,以发出集合和 get 方法中的事件。