gpt4 book ai didi

javascript - 通过组合创建的对象上的方法无法访问所有属性

转载 作者:行者123 更新时间:2023-11-29 20:46:42 27 4
gpt4 key购买 nike

我正在为产品构建一个家庭的概念,成员有不同类型(accountHolderpayingCustomerstudent、等等)。最初我将它们构建为 FamilyMember 的子类,但我最终得到了一些重复的代码并最终遇到了一个重大问题:我们平台的 student 也可以是唯一的 payingCustomeraccountHolder

鉴于对象组合在 JS 中被广泛吹捧为一个好主意,我决定走那条路。但是,如果属性属于另一个对象类型(例如 student),则特定对象类型(例如 accountHolder)的方法无法访问实例化对象的属性。

为了更加客观,我决定使用以下代码复制该行为:

const person = (props) => {
let state = {
name: props.name,
}

state.isOfAge = () => {
// state.isAdult is always undefined because
// isAdult doesn't exist in this object
return state.isAdult === true
}

return state
}

const adult = (props) => {
return {
isAdult: true,
}
}

const factory = (props) => {
return Object.assign({}, person(props), adult(props))
}

const john = factory({
name: 'John',
})

console.clear()
console.log(john) // { isAdult: true, name: "John", isOfAge... }
console.log(john.isOfAge()) // false

我期待 john 的方法 isOfAge 能够访问属性 isAdult,因为它在对象中。但是,从概念上讲,我理解为什么它不起作用:isOfAgestate 的一种方法,而不是生成的 adult 实例。

如果我使用的是类,甚至是传统的原型(prototype)/构造函数机制,我知道如何让它工作(例如附加到 prototype)。对于对象组合,我不知道如何实现,可能是因为缺乏 FP 经验。

感谢您的帮助!

最佳答案

您可以在 isOfAge 中使用 this 而不是 state。这样,当方法 isOfAge 被调用时,this 将被推导,它将被绑定(bind)到它被调用的任何对象。不过,您必须使用常规函数而不是箭头函数才能正常工作(箭头函数没有 this):

const person = (props) => {
let state = {
name: props.name,
}

state.isOfAge = function() { // use a regular function
return this.isAdult === true // use this here instead of state
}

return state
}

const adult = (props) => {
return {
isAdult: true,
}
}

const factory = (props) => {
return Object.assign({}, person(props), adult(props))
}

const john = factory({
name: 'John',
})

console.log(john);
console.log(john.isOfAge()); // returns 'true' because 'this' inside 'isOfAge' will be 'john'

关于javascript - 通过组合创建的对象上的方法无法访问所有属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54186635/

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