gpt4 book ai didi

JavaScript:获取和设置对象的嵌套属性

转载 作者:行者123 更新时间:2023-11-30 20:22:07 25 4
gpt4 key购买 nike

网络和 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。我怎样才能让我的类(class)发出事件,这样我就可以像 person.on('change', data => console.log(data));

这样的代码

最佳答案

我建议您使用 ES6 类语法而不是原型(prototype)并实现 set 和 get 作为方法。对于问题 2,没有简单的方法可以做到这一点。您可以使用诸如 pubsub-js 之类的库手动实现它,以在 set 和 get 方法中发出事件。

关于JavaScript:获取和设置对象的嵌套属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51338647/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com