还有关于如何在网络和 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:如何正确获取()和设置()嵌套属性。我希望能够
person.get('addr.street')
和person.set('addr.pin', '123456')
。目前我只能通过在对象创建期间传递它来设置整个 addr 对象。
Q2。我怎样才能让我的班级发出事件,这样我就可以像这样编写代码person.on('change', data => console.log(data));