gpt4 book ai didi

Javascript组合如何扩展一个对象

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

我正在尝试采用新的 ES6 功能来更好地组合没有类继承的对象。但是,我不明白如何扩展和反对或覆盖函数。下面的代码使用 Object.assign() 的组合模式。

问题:如何在不复制整个 TextCell 对象的情况下创建第二个对象工厂 UnderlinedCell。它的行为类似于 TextCell,只是 getHeight 返回 getHeight + 1 并且 draw 方法添加了一 strip 有破折号“-”的线。

我为什么要这样做?:我正在努力了解这个视频中解释的构图概念 Composition over Inheritance from Johansson

下面是对象工厂 TextCell 的代码。

const getHeight = (state) => ({
getHeight: () => state.text.length
})

const draw = (state) => ({
draw: () => state.text.join(" | ")
})

const TextCell = (text) => {
let state = {
text: text.split("\n")
}

return Object.assign(getHeight(state), draw(state))
}

console.log("The height of the cell is %s", TextCell("foo\nbar").getHeight())
console.log(TextCell("foo\nbar").draw())

最佳答案

首先,state 是私有(private)的。这意味着我们只能使用 TextCell 公开的公共(public)方法,即 getHeightdraw

现在,UnderlineCell 是一个函数,它组合了 TextCell扩展 TextCell 的实现。 例如

const getHeight = (state) => ({
getHeight: () => state.text.length
})

const draw = (state) => ({
draw: () => state.text.join(" | ")
})

const TextCell = (text) => {
const state = {
text: text.split("\n")
}

return Object.assign(getHeight(state), draw(state))
}


const UnderlineCell = (text) => {
const textCell = TextCell(text);
const getHeight = () => textCell.getHeight() + 1;
const line = '\n------\n';
const draw = () => textCell.draw().replace(' | ', line) + line;

return {...textCell, getHeight, draw};
}

const uCell = UnderlineCell('hello\nthis');
console.log(uCell.draw());

关于Javascript组合如何扩展一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49719100/

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